﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections.Generic;
using System.IO;

using CE.User;
using CE.Global;
using CE.Database;
using CE.CarInsurance;
using CE.Mail;
using CE.InputOut;

public partial class carinsurance_fleet_FleetManualQuote : System.Web.UI.Page
{
    //int _currentRow = 0;
    Int64 CompanyId = 0;
    Int64 FleetCarId = 0;

    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    private DateTime dateTimeNow = CE.Global.General.GetUTCDateTime();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/SiteUserSecureLogin.aspx");
        }

        if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "201")
        {
            Response.Redirect("~/carinsurance/PendingApplication.aspx");
        }

        if (!IsPostBack)
        {
            CE.User.AccountStatusDB _accountStatusDB = new CE.User.AccountStatusDB();
            int _pwdStatus = _accountStatusDB.GetLastPasswordChagedStatus(Convert.ToInt64(Session[CE.Global.General.UserId].ToString()));
            if (_pwdStatus == 1)
            {
                Response.Redirect("~/User/ChangePassword.aspx");
            }

            txtGG.Text = "PROVIDER";
            //For monthly Installment -- start
            ddlGGDiscount.Items.Clear();
            ddlGGDiscount.Items.Add(new ListItem(0 + " %", "0"));
            ddlNoofInstallments.Items.Clear();
            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
            lblCreditCardAllowed.Text = "1. " + Resources.CarInsurance.BankK;
            lblCreditCardAllowed.ForeColor = System.Drawing.Color.Green;

            lblInterest.Text = Resources.CarInsurance.InterestFree;
            //For monthly Installment -- End


            if (Request.QueryString["tabid"] != null)
            {
                hidLastTab.Value = Request.QueryString["tabid"].ToString();
            }
            if (Request.QueryString["CompanyId"] != null)
            {
                txtCompanyId.Text = Request.QueryString["CompanyId"].ToString();
            }
            else
            {
                Response.Redirect("FleetCompanyList.aspx");
            } if (Request.QueryString["FleetCarId"] != null)
            {
                txtFleetCarId.Text = Request.QueryString["FleetCarId"].ToString();
            }
            else
            {
                txtFleetCarId.Text = "0";
            }      
            ResetAll();
            LoadgentbyAdmin();
            LoadControlData();
            if (ddlAgentbyAdmin.Items.Count > 1)
            {
                if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "100")
                {
                    if (Session[General.UserId] != null)
                    {
                        ddlAgentbyAdmin.Text = Session[General.UserId].ToString();
                        ddlAgentbyAdmin.Enabled = false;
                    }
                    else
                    {
                        ddlAgentbyAdmin.Enabled = true;
                    }
                }
                else
                {
                    ddlAgentbyAdmin.Enabled = true;
                }
            }
            txtAgentId.Text = "0";
            if (Request.QueryString["CompanyId"] != null)
            {
                txtCompanyId.Text = Request.QueryString["CompanyId"].ToString();
                string strSql = @"SELECT AgentId,CompanyName FROM tblFleetCompany WHERE CompanyId = " + txtCompanyId.Text.Trim();
                MyDatabase _db = new MyDatabase();
                DataTable _SelectItemResult = _db.GetDataTable(strSql);
                if (_SelectItemResult != null && _SelectItemResult.Rows.Count > 0)
                {
                    if (_SelectItemResult.Rows[0]["AgentId"] != DBNull.Value)
                    {
                        txtAgentId.Text = _SelectItemResult.Rows[0]["AgentId"].ToString();
                    }
                    if (_SelectItemResult.Rows[0]["CompanyName"] != DBNull.Value)
                    {
                        lblPageName.Text += " - " + _SelectItemResult.Rows[0]["CompanyName"].ToString();
                    }
                }
            }

            if (!Int64.TryParse(txtCompanyId.Text.Trim(), out CompanyId))
            {
                CompanyId = 0;
            }
            if (!Int64.TryParse(txtFleetCarId.Text.Trim(), out FleetCarId))
            {
                FleetCarId = 0;
            }
            if (CompanyId > 0 && FleetCarId > 0)
            {
                divCXBrokerPremium.Visible = true;
                divCarDetailList.Visible = true;
                LoadCarGrid(CompanyId, 0);
                //gvCarDetailList.DataBind();
                SetGVCarDetailSelectedIndex(FleetCarId);
            }
            else if (CompanyId > 0 && FleetCarId == 0)
            {
                divCXBrokerPremium.Visible = true;
                divCarDetailList.Visible = true;
                LoadCarGrid(CompanyId, FleetCarId);
                //gvCarDetailList.DataBind();
                if (gvCarDetailList.Rows.Count > 0)
                {
                    SetGVCarDetailSelectedIndex();
                }
                else
                {
                    btnDownLoadQuotation.Enabled = false;
                    chkConfirmEmail.Enabled = false;
                    btnSendQuotation.Enabled = false;
                    divCXBrokerPremium.Visible = false;
                    lblCallSessionName.Text += "<br/><br/>" + Resources.General.NORECORDFOUND;
                    lblCallSessionName.Text += "<br/><br/>INVALID. NOT FOUND! CHECK CX IT TEAM.";
                }
            }
            else
            {
                btnDownLoadQuotation.Enabled = false;
                chkConfirmEmail.Enabled = false;
                btnSendQuotation.Enabled = false;
                divCXBrokerPremium.Visible = false;
                lblCallSessionName.Text += "<br/><br/>" + Resources.General.NORECORDFOUND;
                lblCallSessionName.Text += "<br/><br/>INVALID. NOT FOUND! CHECK CX IT TEAM.";
            }
            ShowLastQuotationSendDate(CompanyId);
        }
    }

    #region Button Click

    protected void btnCustomerDetailRemark_Click(object sender, EventArgs e)
    {
        try
        {
            
        }
        catch (Exception Ex)
        {
        }
    }

    protected void btnSubmitPremium_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt32(lblCarMoreDetailID.Text) > 0)
        {
            btnSubmitPremium.Enabled = false;
            btnNewPremium.Enabled = false;
            btnEditSubmit.Enabled = false;
            lblPremiumMessage.Text = Resources.General.NonGGFoundAppDetailSubmission;
            lblPremiumMessage.ForeColor = System.Drawing.Color.Red;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.NonGGFoundAppDetailSubmission + "');", true);
            return;
        }

        if (chkCompanyStaff.Checked && Session[General.UserRole].ToString() == "100")
        {
            lblPremiumMessage.Text = "You are NOT allowed to update this premium for Company Staff.";
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('You are NOT allowed to update this premium for Company Staff.');", true);
            return;
        }

        DateTime _dtCoverCommDate = dateTimeNow;
        if (DateTime.TryParse(lblEditCoverCommencementDate.Text, out _dtCoverCommDate))
        {
            DateTime _dtNow = new DateTime(dateTimeNow.Year, dateTimeNow.Month, dateTimeNow.Day);

            if (DateTime.Compare(_dtNow, _dtCoverCommDate) > 0)
            {
                lblPremiumError.Text = Resources.General.CommencementCheck;
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.CommencementCheck + "');", true);
                return;
            }
            else
            {
                lblEditCoverCommencementDateCaption.ForeColor = System.Drawing.Color.Gray;
                lblEditCoverCommencementDateMessage.Text = string.Empty;
            }
        }
        else
        {
            lblPremiumError.Text = Resources.General.CommencementCheck;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.CommencementCheck + "');", true);
            return;
        }

        float _sumInsured = 0.0f;
        if (!float.TryParse(txtOwnDamage.Text, out _sumInsured))
        {
            lblPremiumError.Text = Resources.General.SumInsurredNotValid;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.SumInsurredNotValid + "');", true);
            return;
        }

        decimal _InstalmentPremiumWOD = 0;
        if (!decimal.TryParse(lblTotalGrossPremiumWOD.Text, out _InstalmentPremiumWOD))
        {
            _InstalmentPremiumWOD = 0;
        }
        if (_InstalmentPremiumWOD <= 0 && ddlPaymentOption.Text == "IP")
        {
            lblPremiumError.Text = Resources.General.PayMsg_NoInstallment;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.PayMsg_NoInstallment + "');", true);
            return;
        }
        if (!GGSpecialPremiumValidation())
        {
            lblPremiumError.Text = "NCB less then 50%, Can NOT select this premium.";
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('NCB less then 50%, Can NOT select this premium.');", true);
            return;
        }
        Page.Validate("premium");

        if ((Convert.ToInt32(txtPremiumId.Text) > 0) || (Convert.ToInt32(txtPremiumId.Text) <= 0 && grvPremiumList.Rows.Count < 1))
        {
            if (IsValid)
            {
                Int64 _result = 0;
                string _ProductType = "CIN";
                FleetBrokerPremium _fleetbrokerPremium = new FleetBrokerPremium();
                FleetBrokerPremiumDB _fleetbrokerPremiumdb = new FleetBrokerPremiumDB();
                _fleetbrokerPremium.FleetBrokerPremiumId = Convert.ToInt64(txtPremiumId.Text);
                _fleetbrokerPremium.CXBrokerProviderId = Convert.ToInt64(ddlBrokerProvider.Text);
                _fleetbrokerPremium.ProviderCoverTypeId = Convert.ToInt64(ddlBrokerCoverType.Text);
                _fleetbrokerPremium.FleetCarId = Convert.ToInt64(txtFleetCarId.Text);
                _fleetbrokerPremium.CompanyId = Convert.ToInt64(txtCompanyId.Text);

                if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "100")
                {
                    _fleetbrokerPremium.AgentId = Convert.ToInt64(txtAgentId.Text);
                }
                else if (ddlAgentbyAdmin.Text != "0")
                {
                    _fleetbrokerPremium.AgentId = Convert.ToInt64(ddlAgentbyAdmin.Text);
                }
                else
                {
                    _fleetbrokerPremium.AgentId = Convert.ToInt64(txtAgentId.Text);
                }
                _fleetbrokerPremium.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                _fleetbrokerPremium.Premium = Convert.ToSingle(txtNetPremium.Text);

                _fleetbrokerPremium.SelectedStatus = chkSelected.Checked;
                _fleetbrokerPremium.WorkShop = ddlGarageType.Text;
                _fleetbrokerPremium.ProductType = _ProductType;
                _fleetbrokerPremium.TotalVMI = Convert.ToSingle(txtGrossPremium.Text);

                _fleetbrokerPremium.IsIncludeCMI = chkCTPL.Checked;

                if (chkCTPL.Checked)
                {
                    _fleetbrokerPremium.TotalCMI = Convert.ToSingle(txtCTPL.Text);
                }
                else
                {
                    _fleetbrokerPremium.TotalCMI = 0;
                }
                _fleetbrokerPremium.DiscountPercentage = Convert.ToInt16(ddlDiscountPercentage.Text);


                _fleetbrokerPremium.SumInsured = Convert.ToInt32(_sumInsured.ToString("#0"));
                if (_sumInsured > 1000)
                {
                    _fleetbrokerPremium.OwnDamage = _sumInsured.ToString("#,000");
                }
                else
                {
                    _fleetbrokerPremium.OwnDamage = _sumInsured.ToString("#0");
                }

                _fleetbrokerPremium.AnnualPremium = Convert.ToSingle(txtAnnualPremium.Text);
                _fleetbrokerPremium.TPPD = txtTPPD.Text;
                _fleetbrokerPremium.TPBIP = txtTPBIP.Text;
                _fleetbrokerPremium.TPBIA = txtTPBIA.Text;
                _fleetbrokerPremium.DEC = txtDeductible.Text;
                _fleetbrokerPremium.FireTheft = txtFireTheft.Text;

                _fleetbrokerPremium.PADriver = txtPA.Text;
                _fleetbrokerPremium.MedicalExpense = txtMED.Text;
                _fleetbrokerPremium.BailBound = txtBailBond.Text;

                _fleetbrokerPremium.Info1 = lblQRefNo.Text;
                _fleetbrokerPremium.Info2 = txtEditLicensePlate.Text;
                _fleetbrokerPremium.Info3 = ddlVehicleBodyType.Text;
                _fleetbrokerPremium.Info4 = chkCompanyStaff.Checked ? "1" : "0";
                _fleetbrokerPremium.Info5 = txtFloodCoverAmount.Text;
                _fleetbrokerPremium.Info6 = chkNamedDriver.Checked ? "1" : "0";
                _fleetbrokerPremium.Info7 = txtAccModCost.Text;
                _fleetbrokerPremium.Info8 = txtPremiumChangeComments.Text;

                _fleetbrokerPremium.PaymentOption = "FP";
                if (ddlPaymentOption.Text != "-1")
                {
                    _fleetbrokerPremium.PaymentOption = ddlPaymentOption.Text;
                }
                _fleetbrokerPremium.NoofInstallment = Convert.ToInt32(ddlNoofInstallments.Text);
                _fleetbrokerPremium.Bank = ddlCreditCard.Text;
                float _ipFAPremiumWD = 0.0f;
                if (!float.TryParse(lblTotalGrossPremiumWD.Text, out _ipFAPremiumWD))
                {
                    _ipFAPremiumWD = 0.0f;
                }
                _fleetbrokerPremium.IPFinalAnnualPremiumWD = _ipFAPremiumWD;
                _fleetbrokerPremium.InstallmentAmountWD = Convert.ToSingle(lblFirstInstallmentWD.Text);
                _fleetbrokerPremium.LastInstallmentAmountWD = Convert.ToSingle(lblLastInstallmentWD.Text);
                _fleetbrokerPremium.IPFinalAnnualPremiumWOD = Convert.ToSingle(lblTotalGrossPremiumWOD.Text);
                _fleetbrokerPremium.InstallmentAmountWOD = Convert.ToSingle(lblFirstInstallmentWOD.Text);
                _fleetbrokerPremium.LastInstallmentAmountWOD = Convert.ToSingle(lblLastInstallmentWOD.Text);

                if (ddlPaymentOption.Text == "IP")
                {
                    if (_ipFAPremiumWD > 0)
                    {
                        _fleetbrokerPremium.FinalAnnualPremium = _fleetbrokerPremium.IPFinalAnnualPremiumWD;
                    }
                    else
                    {
                        _fleetbrokerPremium.FinalAnnualPremium = _fleetbrokerPremium.IPFinalAnnualPremiumWOD;
                    }
                    _fleetbrokerPremium.FinalAnnualPremiumNoDisc = _fleetbrokerPremium.IPFinalAnnualPremiumWOD;

                    _fleetbrokerPremium.FinalAnnualPremiumWD = Convert.ToSingle(txtFinalAnnualPremium.Text);
                    _fleetbrokerPremium.FinalAnnualPremiumWOD = Convert.ToSingle(txtFinalAnnualPremiumNoDisc.Text);
                }
                else
                {
                    _fleetbrokerPremium.FinalAnnualPremium = Convert.ToSingle(txtFinalAnnualPremium.Text);
                    _fleetbrokerPremium.FinalAnnualPremiumNoDisc = Convert.ToSingle(txtFinalAnnualPremiumNoDisc.Text);

                    _fleetbrokerPremium.FinalAnnualPremiumWD = Convert.ToSingle(txtFinalAnnualPremium.Text);
                    _fleetbrokerPremium.FinalAnnualPremiumWOD = Convert.ToSingle(txtFinalAnnualPremiumNoDisc.Text);
                }

                _fleetbrokerPremium.OriginalPremiumWD = Convert.ToSingle(lblB4EditFinalAnnualPremium.Text);
                _fleetbrokerPremium.OriginalPremiumWOD = Convert.ToSingle(lblB4EditFinalAnnualPremiumNoDisc.Text);
                _fleetbrokerPremium.ApprovedPremium = _fleetbrokerPremium.FinalAnnualPremium;
                _fleetbrokerPremium.TescoAmount = Convert.ToSingle(txtTescoAmount.Text);
                _fleetbrokerPremium.Approved = 0;

                _result = _fleetbrokerPremiumdb.Insert(_fleetbrokerPremium);
                if (_result > 0)
                {
                    if (chkSelected.Checked)
                    {
                        lblSelectedRefNo.Text = lblQRefNo.Text;
                    }
                    txtPremiumId.Text = _result.ToString();
                    lblPremiumError.Text = "";
                    lblPremiumMessage.Text = "Successfully Updated";

                    grvQuoteList.DataBind();
                    grvPremiumList.DataBind();
                    if (grvPremiumList.Rows.Count > 0)
                    {
                        lblAppStatusMessage.Text = "( " + grvPremiumList.Rows.Count.ToString() + " ) record(s) found.";
                    }
                    else
                    {
                        lblAppStatusMessage.Text = "No records found.";
                        hplPremiumDownLoad.Visible = false;
                    }
                    hplPremiumDownLoad.NavigateUrl = "PremiumDownload.aspx?carid=" + txtCarId.Text;
                }
                else
                {
                    txtPremiumId.Text = "0";
                    lblPremiumError.Text = "Updated Failed";
                    lblPremiumMessage.Text = "";
                }
            }
        }
        else
        {
            //lblPremiumError.Text = "Please create only MAX 4 quotations!";
            lblPremiumError.Text = "Please create only one quotation!";
        }
    }

    protected void btnCar_Click(object sender, EventArgs e)
    {
        //Response.Redirect(lblResetUrl.Text.ToString());
        Response.Redirect("NewFleetCar.aspx?CompanyId=" + txtCompanyId.Text.Trim());
    }

    protected void btnCompany_Click(object sender, EventArgs e)
    {
        Response.Redirect("FleetCompanyList.aspx?CompanyId=" + txtCompanyId.Text.Trim());
    }

    protected void btnEditSubmit_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt32(lblCarMoreDetailID.Text) > 0)
        {
            btnSubmitPremium.Enabled = false;
            btnNewPremium.Enabled = false;
            btnEditSubmit.Enabled = false;
            lblPremiumMessage.Text = Resources.General.NonGGFoundAppDetailSubmission;
            lblPremiumMessage.ForeColor = System.Drawing.Color.Red;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.NonGGFoundAppDetailSubmission + "');", true);
            return;
        }

        Page.Validate("editdetail");
        if (Page.IsValid)
        {
            MyDatabase _myDB = new MyDatabase();

            string _strUpdateSQL = "UPDATE tblFleetCarDetail SET ";

            _strUpdateSQL += " Info15 = '" + txtEditLicensePlate.Text + "', ";
            _strUpdateSQL += " Info16 = '" + ddlEditNCB.Text + "', ";
            _strUpdateSQL += " Info17 = '" + ddlEditNamedDriver.Text + "', ";
            _strUpdateSQL += " Info19 = '" + ddlEditCoverCommencementDate.Text + "' ";
            _strUpdateSQL += " WHERE FleetCarId = " + txtFleetCarId.Text + " AND CompanyId = " + txtCompanyId.Text;

            int _retValue = _myDB.ExecuteNonSqlStatement(_strUpdateSQL);
            if (_retValue > 0)
            {
                lblEditDetailMessage.Text = "Updating succeeded";
                lblEditLicensePlate.Text = txtEditLicensePlate.Text;
                lblEditCoverCommencementDate.Text = ddlEditCoverCommencementDate.Text;
                lblEditCoverCommencementDateMessage.Text = string.Empty;
                LoadDiscountPercentageList();
            }
            else
            {
                lblEditDetailMessage.Text = "Updating failed";
            }

        }
    }

    protected void btnGoBack_Click(object sender, EventArgs e)
    {
        //Response.Redirect("~/carinsurance/ViewCICustomerCallNew.aspx?leadid=" + lblAgentLeadID.Text + "&calltype=" + lblCallType.Text);
    }

    protected void btnGoToApplication_Click(object sender, EventArgs e)
    {
        if (lblSelectedRefNo.Text != string.Empty)
        {
            if (lblRenewalStaus.Text == "0")
            {
                Response.Redirect("~/carinsurance/fleet/FleetApplication.aspx?CompanyId=" + txtCompanyId.Text.Trim() + "&refno=" + lblQRefNo.Text);
            }
            else
            {
                if (lblLastYearRefNo.Text != string.Empty)
                {
                    Response.Redirect("~/carinsurance/fleet/FleetApplication.aspx?CompanyId=" + txtCompanyId.Text.Trim() + "&refno=" + lblQRefNo.Text + "&lyrrefno=" + lblLastYearRefNo.Text);
                }
            }
        }
        else
        {
            Int32 _CancelStatus = 0;
            string _QuoteRefNo = "";
            MyDatabase _db = new MyDatabase();
            string _strSelect = @"SELECT CASE WHEN MD.CancelStatus IS NULL THEN 0 ELSE MD.CancelStatus END AS CancelStatus "
                                + "FROM tblFleetCarMoreDetails MD INNER JOIN tblFleetBrokerPremium BR ON BR.FleetCarId = MD.FleetCarId AND BR.SelectedStatus = 1 "
                                + "WHERE BR.FleetCarId = " + txtFleetCarId.Text;
            DataTable _dtSelect = new DataTable("dtSelect");
            _dtSelect = _db.GetDataTable(_strSelect);
            if (_dtSelect != null && _dtSelect.Rows.Count > 0)
            {
                _CancelStatus = Convert.ToInt32(_dtSelect.Rows[0]["CancelStatus"].ToString());
            }
            _dtSelect = null;
            _dtSelect = new DataTable("dtSelect");
            _strSelect = @"SELECT Info1 AS QuoteRefNo FROM tblFleetBrokerPremium WHERE SelectedStatus = 1  AND FleetCarId = " + txtFleetCarId.Text;
            _dtSelect = _db.GetDataTable(_strSelect);
            if (_dtSelect != null && _dtSelect.Rows.Count > 0)
            {
                _QuoteRefNo = _dtSelect.Rows[0]["QuoteRefNo"].ToString();
            }
            if (_CancelStatus == 0 && _QuoteRefNo.ToString() != string.Empty)
            {
                if (lblRenewalStaus.Text == "0")
                {
                    Response.Redirect("~/carinsurance/fleet/FleetApplication.aspx?CompanyId=" + txtCompanyId.Text.Trim() + "&refno=" + _QuoteRefNo.ToString());
                }
                else
                {
                    if (lblLastYearRefNo.Text != string.Empty)
                    {
                        Response.Redirect("~/carinsurance/fleet/FleetApplication.aspx?CompanyId=" + txtCompanyId.Text.Trim() + "&refno=" + _QuoteRefNo.ToString() + "&lyrrefno=" + lblLastYearRefNo.Text);
                    }
                }
            }
            else
            {
                if (hidLastTab.Value != "3")
                {
                    lblPremiumMessage.Text = "Please select a quotation for customer.";
                    lblPremiumMessage.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    hidLastTab.Value = "";
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Please select a quotation for customer.');", true);
                }
            }
        }
    }

    protected void btnBuyNowRefresh_Click(object sender, EventArgs e)
    {
        Session[General.CallPageStartDateTime] = lblStartDateTime.Text;
        lblResetUrl.Text = lblResetUrl.Text.Replace("&buynowrefresh=true", "");
        Response.Redirect(lblResetUrl.Text + "&buynowrefresh=true");
    }

    protected void btnNewPremium_Click(object sender, EventArgs e)
    {
        ddlBrokerProvider.Items.Clear();
        LoadBrokerProvider();
        ClearFields();
        txtGG.Text = "PROVIDER";
        txtTescoAmount.Text = "0";
        if ((Convert.ToInt32(txtPremiumId.Text) > 0) || (Convert.ToInt32(txtPremiumId.Text) <= 0 && grvPremiumList.Rows.Count < 4))
        {
            lblPremiumError.Text = string.Empty;
            lblPremiumMessage.Text = string.Empty;
        }
        else
        {
            lblPremiumMessage.Text = string.Empty;
            lblPremiumError.Text = "Please create only Max 4 quotations!";
        }
    }

    protected void btnDownLoadQuotation_Click(object sender, EventArgs e)
    {
        try
        {
            if (grvQuoteList.Rows.Count > 0)
            {
                
                Int32 NoofSelected = 0;
                string ResultIdList = "";
                for (int i = 0; i < grvQuoteList.Rows.Count; i++)
                {
                    GridViewRow row = grvQuoteList.Rows[i];
                    bool isSendChecked = ((CheckBox)row.FindControl("chkSend")).Checked;
                    string _CarId = ((Label)row.FindControl("lblSendFleetCarId")).Text;
                    if (isSendChecked)
                    {
                        ResultIdList = ResultIdList + _CarId + ",";
                        NoofSelected = NoofSelected + 1;
                    }
                }
                if (NoofSelected <= 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "Send Quotation", "alert('No item to download!');", true);
                    return;
                }
                else if (NoofSelected > 0)
                {
                    
                    string FleetCarIds = "";
                    FleetCarIds = ResultIdList.Substring(0, ResultIdList.Length - 1);
                    GenerateQuoteFile("DOWNLOAD", FleetCarIds);
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    protected void btnSendQuotation_Click(object sender, EventArgs e)
    {
        try
        {
            Int16 IsThai = 1;
            if (chkIsEN.Checked)
            {
                IsThai = 0;
            }

            if (IsThai == 1)
            {
                Session["Language"] = "th-TH";
            }
            else
            {
                Session["Language"] = "en-US";
            }

            String selectedCulture = CE.Global.General.SetCulture();
            base.InitializeCulture();
            if (grvQuoteList.Rows.Count > 0)
            {
                bool Status = false;
                Int32 NoofSelected = 0;
                string ResultIdList = "";
                for (int i = 0; i < grvQuoteList.Rows.Count; i++)
                {
                    GridViewRow row = grvQuoteList.Rows[i];
                    bool isSendChecked = ((CheckBox)row.FindControl("chkSend")).Checked;
                    string _CarId = ((Label)row.FindControl("lblSendFleetCarId")).Text;
                    if (isSendChecked)
                    {
                        ResultIdList = ResultIdList + _CarId + ",";
                        NoofSelected = NoofSelected + 1;
                    }
                }
                if (NoofSelected <= 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "Send Quotation", "alert('No item to download!');", true);
                    return;
                }
                else if (NoofSelected > 0)
                {
                    string FleetCarIds = "";
                    FleetCarIds = ResultIdList.Substring(0, ResultIdList.Length - 1);
                    string _fileName = GenerateQuoteFile("SEND", FleetCarIds);

                    if (_fileName != string.Empty)
                    {
                        FileInfo file = new System.IO.FileInfo(_fileName);
                        FleetBrokerPremiumDB _fleetpremiumDB = new FleetBrokerPremiumDB();

                        if (file.Exists)
                        {
                            string[] _file = new string[1];
                            _file[0] = _fileName;

                            string _toemail = txtConfirmEmail.Text.Trim().ToLower();
                            string _ccemail = string.Empty;
                            if (Session[General.UserRole].ToString() == "100")
                            {
                                _ccemail += Session[General.SMTPReplyTo].ToString();
                            }

                            string _bccemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
                            string _customerName = lblName.Text + " " + lblLastName.Text;
                            string imgUrl = "http://" + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
                            string _emailTitle = string.Empty;
                            string mailBody = "";

                            if (IsThai == 1)
                            {
                                // "Khun. " + _customerName + ", License Plate: " + txtLicensePlate.Text + " Quotation at " + DateTime.Now.ToString("dd/MMM/yyyy");
                                _emailTitle = "GluayGluay.com: ใบเสนอราคาประกันรถยนต์ คุณ " + lblName.Text + " FLEET" + Convert.ToInt64(txtCompanyId.Text).ToString("000");
                                mailBody = @"เรียน คุณ <strong>" + _customerName + "</strong><br/><br/>" +
                                "<a href='http://www.gluaygluay.com'>GluayGluay.com</a> ขอส่งใบเสนอราคาแบบประกันรถยนต์ให้คุณ " + _customerName + " ได้ทำการเปรียบเทียบและตัดสินใจ<br/> " +
                                "หากท่านต้องการที่จะซื้อหรือต้องการสอบถามรายละเอียดเพิ่มเติม กรุณาติดต่อ <strong>" + Session[General.UserName] + "</strong> ได้ที่หมายเลขโทรศัพท์ <strong>" + Session[General.UserPhoneNo].ToString() + "</strong>";

                                if (Session[General.UserGender] == null)
                                {
                                    mailBody += " ขอบพระคุณค่ะ <br/>";
                                }
                                else if (Session[General.UserGender].ToString() == "M")
                                {
                                    mailBody += " ขอบพระคุณครับ <br/>";
                                }
                                else
                                {
                                    mailBody += " ขอบพระคุณค่ะ <br/>";
                                }

                                mailBody += "<br/>ขอแสดงความนับถือ<br/>" +
                                "<img src='" + imgUrl + "' alt='GluayGluay' width='120' height='100' /><br/>" +
                                "<br/><strong><a href='http://www.gluaygluay.com'>GluayGluay.com</a> Support Team</strong><br/>" +
                                    //Company Name changed
                                "บริษัท คอมแพร์เอ็กซ์เพรส นายหน้าประกันภัย (ประเทศไทย) จำกัด<br/>" +
                                "เลขทะเบียนนายหน้าประกันวินาศภัยนิติบุคคล เลขที่ ว00016/2553<br/>" +
                                "ชั้น 42 อาคารยูไนเต็ด เซ็นเตอร์<br/>" +
                                "เลขที่ 323 ถนนสีลม แขวงสีลม เขตบางรัก กรุงเทพฯ 10500<br/>" +
                                "โทร. 02-268-8222 โทรสาร 02-266-6339<br/>" +
                                "อีเมล์: support@gluaygluay.com<br/>" +
                                "กด Like เพื่อติดตามเราได้ใน Facebook: www.facebook.com/GGmotor";
                            }
                            else if (IsThai == 0)
                            {
                                _emailTitle = "Car Insurance quotation  from gluaygluay.com for " + lblName.Text + " FLEET" + Convert.ToInt64(txtCompanyId.Text).ToString("000");
                                mailBody = @"Dear <strong>" + _customerName + "</strong><br/><br/>" +
                                "<a href='http://www.gluaygluay.com'>Gluaygluay.com</a> would like to send you the quotation of your car insurance for compare and consider " +
                                "If you would like to buy or would like to get any further information kindly contact <strong>" + Session[General.UserName] + "</strong> at our hotline number <strong>" + Session[General.UserPhoneNo].ToString() + "</strong>, thank you very much.";

                                mailBody += "<br/>With best regards,<br/>" +
                                "<img src='" + imgUrl + "' alt='GluayGluay' width='120' height='100' /><br/>" +
                                "<br/><strong><a href='http://www.gluaygluay.com'>Gluaygluay.com</a> Support Team</strong><br/>" +
                                "Comparexpress Insurance Broker ( Thailand ) Ltd,<br/>" +
                                "License number  ว00016/2553<br/>" +
                                "42nd Floor, United Center Building,<br/>" +
                                "323 Silom Road, Bangrak, Bangkok 10500<br/>" +
                                "Tel : 02-268-8222 , Fax : 02-266-6339" +
                                "Email : support@gluaygluay.com<br/>" +
                                "Please click like us to follow all activities at facebook : www.facebook.com/GGmotor";
                            }

                            bool _mailSendingStatus = false;

                            if (Session[General.SMTPAccountName].ToString().Contains("gluaygluay.com"))
                            {
                                _mailSendingStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                            }
                            else if (Session[General.SMTPAccountName].ToString().Contains("comparexpress.co.th"))
                            {
                                _mailSendingStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                            }
                            else if (Session[General.SMTPAccountName].ToString().Contains("gmail.com"))
                            {
                                _mailSendingStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                            }
                            else
                            {
                                _mailSendingStatus = MyMailManager.SendCXMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                            }

                            if (_mailSendingStatus)
                            {
                                if (_fleetpremiumDB.SaveQuotationEmail(Convert.ToInt32(txtCompanyId.Text),
                                    txtConfirmEmail.Text,
                                    Convert.ToInt64(Session[General.UserId].ToString()),
                                    Convert.ToInt16(grvQuoteList.Rows.Count),
                                     1) > 0)
                                {
                                    lblSendQuotationMessage.Text = Resources.General.QuotationSent + " at " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm tt");
                                }
                                else
                                {
                                    lblSendQuotationMessage.Text = Resources.General.QuotationSent + " Saving confirm email failed.";
                                }

                                chkConfirmEmail.Checked = false;
                                chkConfirmEmail_CheckedChanged(sender, e);
                                chkConfirmEmail.Enabled = false;
                            }
                            else
                            {
                                lblSendQuotationMessage.Text = Resources.General.QuotationFailed;
                            }
                        }
                        else
                        {
                            lblSendQuotationMessage.Text = "Excel generating failed.";
                            lblSendQuotationMessage.Text += " " + Resources.General.QuotationFailed;
                        }
                    }
                    else
                    {
                        lblSendQuotationMessage.Text = "Excel generating failed. No item found.";
                        lblSendQuotationMessage.Text += " " + Resources.General.QuotationFailed;
                    }
                }
            }
        }
        catch (Exception ex)
        {
        }
        if (lblLangOption.Text == "1")
        {
            Session["Language"] = "th-TH";
        }
        else
        {
            Session["Language"] = "en-US";
        }

        CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    #endregion

    #region Dropdown List

    protected void ddlVehicleBodyType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlVehicleBodyType.Text == "1")
        {
            txtCTPL.Text = "645.21";
        }
        else if (ddlVehicleBodyType.Text == "2")
        {
            txtCTPL.Text = "967.28";
        }
        else
        {
            txtCTPL.Text = "0";
        }

        txtGrossPremium_TextChanged(sender, e);
    }

    protected void ddlBrokerProvider_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";
        LoadBrokerCoverType();
        lblQRefNo.Text = CE.Global.General.GetFleetReferenceNumber(txtFleetCarId.Text.Trim(), ddlBrokerProvider.Text.Trim());
         ddlBrokerCoverType_SelectedIndexChanged(sender, e);
    }

    protected void ddlBrokerCoverType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlBrokerProvider.Text == "43" && (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11") && txtUserTypeId.Text == "1001")
        {
            ddlGarageType.Items.Clear();
            ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Garage_Authorized, "1"));
            ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        else
        {
            ddlGarageType.Items.Clear();
            ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Garage_Dealer, "2"));
            ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Garage_Authorized, "1"));
            ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        LoadDiscountPercentageList();
        LoadMonthlyInstallment();
        LoadBrokerDefault();

    }

    protected void ddlNoofInstallments_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (ddlBrokerProvider.Text == "29")
            {
                if (ddlCreditCard.Text != "KBANK" && ddlCreditCard.Text != "CHINS")
                {
                    if (ddlNoofInstallments.Text == "4")
                    {
                        lblInterest.Text = "3.2 % " + Resources.CarInsurance.Interest;
                    }
                    else if (ddlNoofInstallments.Text == "6")
                    {
                        lblInterest.Text = "4.8 % " + Resources.CarInsurance.Interest;
                    }
                    else
                    {
                        lblInterest.Text = Resources.CarInsurance.InterestFree;
                    }
                }
                else
                {
                    lblInterest.Text = Resources.CarInsurance.InterestFree;
                }
            }
            lblCHINSMessage.Text = "";
            if (ddlCreditCard.Text == "CHINS")
            {
                if (ddlNoofInstallments.Text == "2")
                {
                    lblCHINSMessage.Text = "(50 : 50)";
                }
                else if (ddlNoofInstallments.Text == "3")
                {
                    lblCHINSMessage.Text = "(40 : 30 : 30)";
                }
                else if (ddlNoofInstallments.Text == "4")
                {
                    lblCHINSMessage.Text = "(25 : 25 : 25 : 25)";
                }
            }
            InstallmentsCalculation();
        }
        catch (Exception Ex)
        {
        }
    }

    protected void ddlCreditCard_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (ddlBrokerProvider.Text == "11")
            {
                if (ddlCreditCard.Text == "CITI")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments_SelectedIndexChanged(null, null);
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments_SelectedIndexChanged(null, null);
                }
            }

            //For K Bank 6 Months Installments 
            decimal _AnnualPremium = 0;
            decimal _AnnualPremiumWOD = 0;
            if (!decimal.TryParse(txtAnnualPremium.Text, out _AnnualPremium))
            {
                _AnnualPremium = 0;
            }
            if (!decimal.TryParse(txtFinalAnnualPremiumNoDisc.Text, out _AnnualPremiumWOD))
            {
                _AnnualPremiumWOD = 0;
            }
            if (_AnnualPremiumWOD < 5000 && ddlCreditCard.Text == "CHINS")
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));

                ddlGGDiscount.Items.Clear();
                ddlGGDiscount.Items.Add(new ListItem("0 %", "0"));
                ddlNoofInstallments_SelectedIndexChanged(null, null);
            }
            else if (_AnnualPremiumWOD >= 5000 && ddlCreditCard.Text == "CHINS")
            {
                Int32 intInstallVal = 0;
                intInstallVal = CheckCommencementDateforCashInstallment();
                if (intInstallVal == 0)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                }
                else if (intInstallVal == 2)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
                else if (intInstallVal == 3)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
                else if (intInstallVal == 4)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }

                ddlGGDiscount.Items.Clear();
                ddlGGDiscount.Items.Add(new ListItem("0 %", "0"));
                ddlNoofInstallments_SelectedIndexChanged(null, null);
            }
            else if (_AnnualPremiumWOD >= 20000 && ddlCreditCard.Text == "KBANK")
            {
                if (ddlBrokerProvider.Text == "32")
                {
                    if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                    {
                        if (ddlNoofInstallments.Text == "3")
                        {
                            ddlNoofInstallments.Items.Clear();
                            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                            ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        }
                        else
                        {
                            ddlNoofInstallments.Items.Clear();
                            ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        }

                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                    }
                }
                else
                {
                    if (ddlBrokerProvider.Text == "29")
                    {
                        string IPDiscount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IPDiscount");
                        ddlGGDiscount.Items.Clear();
                        if (IPDiscount != string.Empty)
                        {
                            ddlGGDiscount.Items.Add(new ListItem(IPDiscount.ToString() + " %", IPDiscount.ToString()));
                        }
                    }
                    if (ddlNoofInstallments.Text == "3")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    }
                }
                ddlNoofInstallments_SelectedIndexChanged(null, null);
            }
            else
            {
                if (ddlBrokerProvider.Text == "11")
                {
                    if (ddlCreditCard.Text == "CITI")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments_SelectedIndexChanged(null, null);
                    }
                    else if (ddlCreditCard.Text == "KBANK")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        ddlNoofInstallments_SelectedIndexChanged(null, null);
                    }
                }
                else if (ddlBrokerProvider.Text == "29")
                {
                    string IPDiscount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IPDiscount");
                    ddlGGDiscount.Items.Clear();
                    if (IPDiscount != string.Empty)
                    {
                        ddlGGDiscount.Items.Add(new ListItem(IPDiscount.ToString() + " %", IPDiscount.ToString()));
                    }
                    ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));
                    if (ddlCreditCard.Text == "KBANK")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        ddlNoofInstallments_SelectedIndexChanged(null, null);
                    }
                    else if (ddlNoofInstallments.Text == "6")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                        ddlNoofInstallments_SelectedIndexChanged(null, null);
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments_SelectedIndexChanged(null, null);
                    }
                }
                else if (ddlBrokerProvider.Text == "32")
                {
                    if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                    {
                        if (ddlCreditCard.Text == "KBANK")
                        {
                            ddlNoofInstallments.Items.Clear();
                            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                            ddlNoofInstallments_SelectedIndexChanged(null, null);
                        }
                        else
                        {
                            ddlNoofInstallments.Items.Clear();
                            ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                            ddlNoofInstallments_SelectedIndexChanged(null, null);
                        }
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                        ddlNoofInstallments_SelectedIndexChanged(null, null);//Sakthi on 25 Oct 2012 -- Added
                    }
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments_SelectedIndexChanged(null, null);//Sakthi on 25 Oct 2012 -- Added
                }
            }

            //For K Bank 6 Months Installments --End
        }
        catch (Exception Ex)
        {
        }
    }

    protected void ddlGarageType_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadBrokerDefault();
    }

    protected void ddlDiscountPercentage_SelectedIndexChanged(object sender, EventArgs e)
    {
        txtGrossPremium_TextChanged(sender, e);
        if (ddlDiscountPercentage.Text == "0")
        {
            txtFinalAnnualPremiumNoDisc.Enabled = false;
        }
        else
        {
            txtFinalAnnualPremiumNoDisc.Enabled = true;
        }
    }

    #endregion

    #region Grid

    protected void gvCarDetailList_OnSorted(object sender, EventArgs e)
    {
        if (gvCarDetailList.Rows.Count > 0)
        {
            gvCarDetailList.SelectedIndex = -1;
            divCustomerPolicyDetail.Visible = false;

            divCompletedQuoteDetails.Visible = false;
        }
    }

    protected void gvCarDetailList_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (gvCarDetailList.SelectedIndex >= 0)
        {
            ResetAll();
            ClearFields();
            lblEditCoverCommencementDateMessage.Text = "";
            lblEditCoverCommencementDateCaption.Font.Bold = false;
            lblEditCoverCommencementDateCaption.ForeColor = System.Drawing.Color.Black;
            hidLastTab.Value = "1";
            GridViewRow _row = gvCarDetailList.SelectedRow;
            ShowCarAndCustomerDetails(Convert.ToInt64(txtCompanyId.Text), Convert.ToInt64(_row.Cells[0].Text), Convert.ToInt64(_row.Cells[1].Text));
            divCustomerPolicyDetail.Focus();
        }
    }

    protected void grvPremiumList_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";
        FleetBrokerPremium _fleetbrokerPremium = new FleetBrokerPremium();
        FleetBrokerPremiumDB _fleetbrokerPremiumdb = new FleetBrokerPremiumDB();
        ClearFields();
        if (grvPremiumList.SelectedIndex >= 0)
        {
            DataKey _dKey = grvPremiumList.SelectedDataKey;
            Int64 _premiumId = Convert.ToInt64(_dKey.Values[0]);
            Int64 _brokerId = Convert.ToInt64(_dKey.Values[1]);
            string _QuoteRefNo = _dKey.Values[3].ToString();
            if (_QuoteRefNo.ToString().Trim().Substring(0, 2) == "GG")
            {
                txtGG.Text = "GGSPECIAL";
            }
            Int64 _AgentId = 0;
            if (!Int64.TryParse(_dKey.Values[2].ToString(), out _AgentId))
            {
                _AgentId = 0;
            }
            if (Session[General.UserRole] != null && Session[General.UserRole].ToString() != "100")
            {
                try
                {
                    ddlAgentbyAdmin.Text = _AgentId.ToString();
                }
                catch (Exception ex)
                {
                    ddlAgentbyAdmin.Text = "0";
                }
            }
            string _ProductType = "CIN";
            Int64 _FleetCarId = Convert.ToInt64(txtFleetCarId.Text);
            Int64 _CompanyId = Convert.ToInt64(txtCompanyId.Text);

            _fleetbrokerPremium = _fleetbrokerPremiumdb.GetBrokerPremiumSingleItem(_premiumId, _brokerId, _FleetCarId, _CompanyId, _ProductType);
            if (_fleetbrokerPremium != null)
            {
                ShowBrokerPremiumDetail(_fleetbrokerPremium, false);
            }
            else
            {
                ClearFields();
            }
        }
        else
        {
            ClearFields();
        }
        _fleetbrokerPremium = null;
        _fleetbrokerPremiumdb = null;
    }

    protected void grvPremiumList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("MyDelete"))
        {
            if (e.CommandArgument != null)
            {
                if (lblCarMoreDetailID.Text == "-1")
                {
                    Int64 _AgentId = 0;
                    Int64 _CXBrokerPremiumId = 0;
                    _CXBrokerPremiumId = Convert.ToInt64(e.CommandArgument);
                    _AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());

                    MyDatabase _db = new MyDatabase();
                    SortedList _paraList = new SortedList();
                    _paraList.Add("@CXBrokerPremiumId", _CXBrokerPremiumId);
                    _paraList.Add("@AgentId", _AgentId);
                    int _effCount = _db.ExecuteNonSqlSP("sprocCXBrokerPremiumDeleteSingleItem", _paraList);
                    if (_effCount > 0)
                    {
                        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete was successful.');", true);
                    }
                    grvQuoteList.DataBind();
                    grvPremiumList.DataBind();

                    if (grvPremiumList.Rows.Count > 0)
                    {
                        lblAppStatusMessage.Text = "( " + grvPremiumList.Rows.Count.ToString() + " ) record(s) found.";
                    }
                    else
                    {
                        lblAppStatusMessage.Text = "No records found.";
                    }

                    lblPremiumError.Text = "";
                    lblPremiumMessage.Text = "";
                    txtPremiumId.Text = "0";
                    txtNetPremium.Text = "";
                    ddlDiscountPercentage.Text = "0";
                    ddlGarageType.Text = "-1";
                    chkSelected.Checked = false;
                    ddlBrokerProvider.SelectedIndex = 0;
                    ddlBrokerCoverType.SelectedIndex = 0;
                    ddlBrokerProvider_SelectedIndexChanged(null, null);
                    uplPremiumList.Update();
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete failed. Found application details.');", true);
                }
            }
        }
    }

    #endregion

    #region Postback Methods

    protected void txtGrossPremium_TextChanged(object sender, EventArgs e)
    {
        try
        {
            decimal _premium = 0;
            decimal _netPremiumround = 0;
            txtVAT.Text = "";
            txtTax.Text = "";
            txtNetPremium.Text = "";
            txtAnnualPremium.Text = "";
            lblTax.Text = "0";
            lblVAT.Text = "0";
            lblNetPremium.Text = "0";
            lblAnnualPremium.Text = "0";

            if (decimal.TryParse(txtGrossPremium.Text, out _premium))
            {
                if (_premium <= 5000)
                {
                    ddlDiscountPercentage.Text = "0";
                    ddlDiscountPercentage.Enabled = false;
                }
                else
                {
                    ddlDiscountPercentage.Enabled = true;
                }
                decimal _grossPremium = _premium;
                decimal _netPremium = _premium / 1.07M / 1.004M;

                _netPremium = Math.Floor(_netPremium);
                _netPremium = Math.Round(_netPremium);
                txtNetPremium.Text = _netPremium.ToString("#0.00");
                decimal _tax = 0;
                _tax = Convert.ToDecimal(_netPremium * (0.4M / 100.0M));
                _tax = Math.Ceiling(_tax);
                if (_tax >= 1000)
                {
                    lblTax.Text = _tax.ToString("#,000.00");
                }
                else
                {
                    lblTax.Text = _tax.ToString("#0.00");
                }
                txtTax.Text = _tax.ToString("#0.00");

                decimal _vat = 0;
                _vat = Convert.ToDecimal((_netPremium + _tax) * Convert.ToDecimal(7.0 / 100.0));
                if (_vat >= 1000)
                {
                    lblVAT.Text = _vat.ToString("#,000.00");
                }
                else
                {
                    lblVAT.Text = _vat.ToString("#0.00");
                }
                txtVAT.Text = _vat.ToString("#0.00");
                if (_netPremium >= 1000)
                {
                    lblNetPremium.Text = _netPremium.ToString("#,000.00");
                }
                else
                {
                    lblNetPremium.Text = _netPremium.ToString("#0.00");
                }
                _netPremium = _grossPremium - (_vat + _tax);
                decimal _annualPremium = 0;
                decimal _annualPremiumNoDisc = 0;
                _annualPremiumNoDisc = _netPremium + _vat + _tax;
                _netPremiumround = Math.Round(_netPremium);
                _netPremiumround = Math.Floor(_netPremiumround);
                if (_annualPremiumNoDisc < 5000)
                {
                    if (lblRenewalStaus.Text == string.Empty || lblRenewalStaus.Text == "0")
                    {
                        ddlDiscountPercentage.Text = "0";
                        ddlDiscountPercentage.Enabled = false;
                    }
                }
                if (ddlDiscountPercentage.Text != "0" && Convert.ToInt32(ddlDiscountPercentage.Text) > 0)
                {
                    decimal _discountAmount = Convert.ToDecimal((_netPremiumround * Convert.ToDecimal(Convert.ToDecimal(ddlDiscountPercentage.Text) / 100.0M)));
                    if (_discountAmount >= 1000)
                    {
                        lblDiscountAmount.Text = _discountAmount.ToString("#,000.00");
                    }
                    else
                    {
                        lblDiscountAmount.Text = _discountAmount.ToString("#0.00");
                    }
                    _annualPremium = (_netPremiumround + _vat + _tax) - _discountAmount;
                }
                else
                {
                    lblDiscountAmount.Text = "0";
                    _annualPremium = _netPremium + _vat + _tax;
                }
                if (_annualPremium >= 1000)
                {
                    lblAnnualPremium.Text = _annualPremium.ToString("#,000.00");
                }
                else
                {
                    lblAnnualPremium.Text = _annualPremium.ToString("#0.00");
                }

                if (chkCTPL.Checked)
                {
                    _annualPremium = _annualPremium + Convert.ToDecimal(txtCTPL.Text);
                    _annualPremiumNoDisc = _annualPremiumNoDisc + Convert.ToDecimal(txtCTPL.Text);
                }

                txtAnnualPremium.Text = _annualPremium.ToString("#0.00");
                txtFinalAnnualPremium.Text = _annualPremium.ToString("#0.00");
                txtFinalAnnualPremiumNoDisc.Text = _annualPremiumNoDisc.ToString("#0.00");

                lblB4EditFinalAnnualPremium.Text = _annualPremium.ToString("#0.00");
                lblB4EditFinalAnnualPremiumNoDisc.Text = _annualPremiumNoDisc.ToString("#0.00");

                InstallmentsCalculation();
                ShowTescoAmount();
            }
        }
        catch (Exception Ex)
        {
            lblPremiumError.Text = Ex.Message;
            Ex = null;
        }
    }

    protected void txtFinalAnnualPremium_TextChanged(object sender, EventArgs e)
    {
        try
        {
            InstallmentsCalculation();
            ShowTescoAmount();
        }
        catch (Exception Ex)
        {
            lblPremiumError.Text = Ex.Message;
            Ex = null;
        }
    }

    protected void txtFinalAnnualPremiumNoDisc_TextChanged(object sender, EventArgs e)
    {
        try
        {
            InstallmentsCalculation();
        }
        catch (Exception Ex)
        {
            lblPremiumError.Text = Ex.Message;
            Ex = null;
        }
    }

    protected void txtCTPL_TextChanged(object sender, EventArgs e)
    {
        txtGrossPremium_TextChanged(sender, e);
    }

    protected void chkCTPL_CheckedChanged(object sender, EventArgs e)
    {
        if (chkCTPL.Checked)
        {
            txtCTPL.Enabled = true;
            ddlVehicleBodyType.Enabled = true;
            ddlVehicleBodyType_SelectedIndexChanged(sender, e);
        }
        else
        {
            txtCTPL.Enabled = false;
            ddlVehicleBodyType.Enabled = false;
            txtGrossPremium_TextChanged(sender, e);
        }
    }

    protected void chkCompanyStaff_CheckedChanged(object sender, EventArgs e)
    {
        LoadDiscountPercentageList();
        if (chkCompanyStaff.Checked)
        {
            ListItem _lstTwelve = ddlDiscountPercentage.Items.FindByValue("12");
            if (_lstTwelve != null)
            {
                ddlDiscountPercentage.Text = "12";
            }
            ListItem _lstFifteen = ddlDiscountPercentage.Items.FindByValue("15");
            if (_lstFifteen != null)
            {
                ddlDiscountPercentage.Text = "15";
            }
            if (ddlBrokerProvider.Text == "41")
            {
                ddlDiscountPercentage.Text = "0";
            }
        }
        else
        {
        }
        ddlDiscountPercentage_SelectedIndexChanged(sender, e);
    }

    protected void chkChangePremium_CheckedChanged(object sender, EventArgs e)
    {
        rfvPremiumChangeComments.Enabled = chkChangePremium.Checked;
        txtFinalAnnualPremiumNoDisc.ReadOnly = !chkChangePremium.Checked;
        txtFinalAnnualPremium.ReadOnly = !chkChangePremium.Checked;
    }

    protected void csvDeductibleValid_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        float _deductible = 0.0f;
        if (ddlBrokerProvider.Text == "43" && ddlBrokerCoverType.Text == "31" && txtUserTypeId.Text == "1001")
        {
            if (txtDeductible.Text.Trim() != "")
            {
                if (!float.TryParse(txtDeductible.Text, out _deductible))
                {
                    _deductible = 0.0f;
                }
                if (_deductible > 0)
                {
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                }
            }
            else
            {
                args.IsValid = false;
            }
        }
    }

    protected void chkConfirmEmail_CheckedChanged(object sender, EventArgs e)
    {
        txtConfirmEmail.Enabled = chkConfirmEmail.Checked;
        btnSendQuotation.Enabled = chkConfirmEmail.Checked;
    }

    #endregion

    #region Void Methods

    private void LoadCarGrid(Int64 CompanyId, Int64 FleetCarId)
    {
        DataSet _dsFleetCar = new DataSet();
        MyDatabase _db = new MyDatabase();
        string _spName = "sprocFleetCarAndPolicyDetailSelectItemList";
        SortedList _spPara = new SortedList();
        _spPara.Add("@CompanyId", CompanyId);
        _spPara.Add("@FleetCarId", FleetCarId);
        _dsFleetCar = _db.GetDataSet(_spName, _spPara);
        if (_dsFleetCar != null && _dsFleetCar.Tables.Count > 0)
        {
            gvCarDetailList.DataSource = _dsFleetCar.Tables[0];
            gvCarDetailList.DataBind();
        }
        else
        {
            gvCarDetailList.DataSource = null;
            gvCarDetailList.DataBind();
        }
    }
    
    private void LoadControlData()
    {
        DateTime time = dateTimeNow;
        lblStartDateTime.Text = time.ToString("dd/MMM/yyyy hh:mm:ss tt"); //Don't use HTML tag inside text
        lblStartDayName.Text = "<b style='color:red;'>" + time.ToString("dddd") + " </b>";

        LoadBrokerProvider();
        LoadBrokerCoverType();

        DateTime _dtNow = dateTimeNow;

        for (int d = 0; d < 60; d++)
        {
            ddlEditCoverCommencementDate.Items.Add(new ListItem(_dtNow.ToString("dd/MMM/yyyy"), _dtNow.ToString("dd/MMM/yyyy")));
            _dtNow = _dtNow.AddDays(1);
        }

        ddlEditCoverCommencementDate.Text = dateTimeNow.ToString("dd/MMM/yyyy");
        lblEditCoverCommencementDate.Text = ddlEditCoverCommencementDate.Text;

        lblResetUrl.Text = Request.Url.ToString();
        ResetAll();
        txtAgentId.Text = Session[General.UserId].ToString();
    }

    private void ShowCarPlateNumber(Int64 CECarID, Int64 CustomerID)
    {
        BrokerPremiumDB _db = new BrokerPremiumDB();
        string _carplateNumber = _db.GetCarPlate(CECarID, CustomerID);
        if (_carplateNumber != string.Empty)
        {
            txtEditLicensePlate.Text = _carplateNumber;
            lblEditLicensePlate.Text = _carplateNumber;
        }
    }

    protected void ResetAll()
    {
        txtCarId.Text = "";
        txtCarPolicyId.Text = "";
        divLinks.Visible = false;

        divCompletedQuoteDetails.Visible = false;
        divCustomerPolicyDetail.Visible = false;
        divEditDetail.Visible = false;
        divPremiumList.Visible = false;
        //btnReset.Visible = false;
    }

    private void SetGVCarDetailSelectedIndex(Int64 FleetCarId)
    {
        bool _foundStatus = false;
        foreach (GridViewRow myRow in gvCarDetailList.Rows)
        {
            Int64 _FleetCarId = Convert.ToInt64(gvCarDetailList.DataKeys[myRow.RowIndex][0]);
            if (_FleetCarId == FleetCarId)
            {
                gvCarDetailList.SelectedIndex = myRow.RowIndex;
                gvCarDetailList_SelectedIndexChanged(null, null);
                _foundStatus = true;
                break;
            }
            else
            {
            }
        }

        if (_foundStatus == false)
        {
            gvCarDetailList.SelectedIndex = 0;
            gvCarDetailList_SelectedIndexChanged(null, null);
        }
    }

    private void SetGVCarDetailSelectedIndex()
    {
        bool _foundStatus = false;
        foreach (GridViewRow myRow in gvCarDetailList.Rows)
        {
            Int64 _FleetCarId = Convert.ToInt64(gvCarDetailList.DataKeys[myRow.RowIndex][0]);
            gvCarDetailList.SelectedIndex = myRow.RowIndex;
            gvCarDetailList_SelectedIndexChanged(null, null);
            _foundStatus = true;
            break;
        }

        if (_foundStatus == false)
        {
            gvCarDetailList.SelectedIndex = 0;
            gvCarDetailList_SelectedIndexChanged(null, null);
        }
    }

    protected void ShowCarAndCustomerDetails(Int64 CompanyId, Int64 FleetCarId, Int64 FleetCarPolicyId)
    {
        if (CompanyId > 0 && FleetCarId > 0 && FleetCarPolicyId > 0)
        {
            txtFleetCarId.Text = FleetCarId.ToString();
            txtFleetCarPolicyId.Text = FleetCarPolicyId.ToString();

            lblRefCarID.Text = FleetCarId.ToString();

            //Checking Application Summary
            MyDatabase _myDb = new MyDatabase();
            SortedList _paraList = new SortedList();
            _paraList.Add("@CompanyId", CompanyId);
            _paraList.Add("@FleetCarId", FleetCarId);
            DataTable _dtApp = new DataTable("tblApp");
            _dtApp = _myDb.GetDataTableBySP("sprocFleetApplicationStatusSelectItem", _paraList);

            lblRenewalStaus.Text = "0";
            lblLastYearRefNo.Text = "";
            if (_dtApp != null && _dtApp.Rows.Count > 0)
            {
                if (_dtApp.Rows[0]["Completed"].ToString() == "1")
                {
                    lblLastYearRefNo.Text = _dtApp.Rows[0]["QuoteRefNo"].ToString();
                    lblRenewalStaus.Text = "1";
                    divLinks.Visible = true;

                    //divCarDetailList.Visible = false; 21 Aug 2013

                    btnNewPremium.Visible = false;
                    btnNewPremiumTwo.Visible = false;

                }
            }

            #region Show Customer and Car Details
            MyDatabase _db = new MyDatabase();
            //Customer Details
            string _strSelect = "SELECT P.ContactPerson, C.Info10 DOB, C.Info9 Gender, P.Email, P.ContactNo1 Mobile, O.TH Occupation,  P.ContactNo2 OtherContact1 "
                                + "FROM tblFleetCompany P "
                                + "INNER JOIN tblFleetCarDetail C ON P.ComPanyId = C.ComPanyId AND C.FleetCarId = " + txtFleetCarId.Text + " "
                                + "INNER JOIN tblOccupationInfo O ON C.Info11 = O.OccupationId "
                                + "WHERE P.CompanyId = " + txtCompanyId.Text;
            DataTable _dtSelect = new DataTable("dtSelect");
            _dtSelect = _db.GetDataTable(_strSelect);
            if (_dtSelect != null && _dtSelect.Rows.Count > 0)
            {
                lblName.Text = _dtSelect.Rows[0]["ContactPerson"].ToString();
                //lblLastName.Text = _dtSelect.Rows[0]["SurName"].ToString();
                lblGender.Text = _dtSelect.Rows[0]["Gender"].ToString() == "M" ? "ชาย" : "หญิง";
                //lblDOB.Text = Convert.ToDateTime(_dtSelect.Rows[0]["DOB"].ToString()).ToString("dd/MMM/yyyy");
                lblDOB.Text = _dtSelect.Rows[0]["DOB"].ToString();
                lblOccupation.Text = _dtSelect.Rows[0]["Occupation"].ToString();
                lblMobileNo.Text = _dtSelect.Rows[0]["Mobile"].ToString();
                lblRefMobile.Text = lblMobileNo.Text;
                lblEmailAddress.Text = _dtSelect.Rows[0]["Email"].ToString();
                lblRefEmail.Text = lblEmailAddress.Text;


            }


            _dtSelect = null;
            _dtSelect = new DataTable("dtSelect");
            bool _IsClaim = false;
            bool _IsAddDriver = false;
            string _vehicleType;
            DateTime _dtCoverCommDate = dateTimeNow;

            _strSelect = "SELECT CP.InsuranceType, CP.GarageType, CP.VehicleType, CP.SumInsured, CP.NCDPercent, CP.IsClaimLastYear, CP.IsCTPL,"
                + " CP.IsAddDriver, CP.NoOfDriver,  CP.CoverageCommenceDate, CP.Info6, CP.Info7, CP.ModifiedDate, CD.Info3, CP.Info8 "
                + " FROM tblFleetCarPolicy CP INNER JOIN tblFleetCarDetail CD ON CD.FleetCarId = CP.FleetCarId "
                + " WHERE CP.CompanyId = " + CompanyId.ToString() + " AND CP.FleetCarId= " + FleetCarId.ToString();
            _dtSelect = _db.GetDataTable(_strSelect);

            if (_dtSelect != null && _dtSelect.Rows.Count > 0)
            {
                lblInsuranceType.Text = "";
                string _strInsType = _dtSelect.Rows[0]["InsuranceType"].ToString().Substring(0, 2);
                if (_strInsType == "10")
                {
                    lblInsuranceType.Text = "1";
                }
                else if (_strInsType == "11")
                {
                    lblInsuranceType.Text = "1+";
                }
                else if (_strInsType == "21")
                {
                    lblInsuranceType.Text = "2+";
                }
                else if (_strInsType == "30")
                {
                    lblInsuranceType.Text = "3";
                }
                else if (_strInsType == "31")
                {
                    lblInsuranceType.Text = "3+";
                }

               

                lblGarageType.Text = _dtSelect.Rows[0]["GarageType"].ToString() == "1" ? Resources.CarInsurance.Garage_Authorized : Resources.CarInsurance.Garage_Dealer;
               
                _vehicleType = _dtSelect.Rows[0]["Info3"].ToString();
                switch (_vehicleType)
                {
                    case "110":
                        lblVehicleType.Text = Resources.CarInsurance.VehicleType_Private;
                        break;
                    case "120":
                        lblVehicleType.Text = Resources.CarInsurance.VehicleType_Commercial;
                        break;
                    case "320":
                        lblVehicleType.Text = Resources.CarInsurance.VehicleType_Pickup;
                        break;
                    default:
                        lblVehicleType.Text = Resources.CarInsurance.VehicleType_Private;
                        break;
                }

                string _strQuoteDate = _dtSelect.Rows[0]["ModifiedDate"].ToString();
                DateTime _dtQuoteDate = dateTimeNow;
                DateTime _dtCompareQuoteDate = dateTimeNow.AddMonths(-1);
                if (DateTime.TryParse(_strQuoteDate, out _dtQuoteDate))
                {
                    lblRefModifiedDateTime.Text = _dtQuoteDate.ToString("dd/MMM/yyyy hh:mm tt");
                    if (DateTime.Compare(_dtCompareQuoteDate, _dtQuoteDate) > 0)
                    {
                        lblQuoteDateTimeStatus.Text = "0";
                        lblQuoteDateTimeStatusMessage.Text = Resources.General.QuoteDateTimeOVER;
                        lblQuoteDateTimeStatusMessage.Font.Bold = true;
                        lblQuoteDateTimeStatusMessage.ForeColor = System.Drawing.Color.Red;
                    }
                    else
                    {
                        lblQuoteDateTimeStatus.Text = "1";
                        lblQuoteDateTimeStatusMessage.Text = Resources.General.QuoteDateTimeOK;
                        lblQuoteDateTimeStatusMessage.Font.Bold = true;
                        lblQuoteDateTimeStatusMessage.ForeColor = System.Drawing.Color.Green;
                    }
                }
                else
                {
                    lblQuoteDateTimeStatus.Text = "0";
                    lblQuoteDateTimeStatusMessage.Text = Resources.General.QuoteDateTimeNOTVALID;
                    lblQuoteDateTimeStatusMessage.Font.Bold = true;
                    lblQuoteDateTimeStatusMessage.ForeColor = System.Drawing.Color.Red;
                }

                lblSumInsured.Text = Convert.ToInt32(_dtSelect.Rows[0]["SumInsured"]).ToString("#,000");
                txtOwnDamage.Text = lblSumInsured.Text;

                lblNCD.Text = _dtSelect.Rows[0]["NCDPercent"].ToString() == "-1" ? "0" : _dtSelect.Rows[0]["NCDPercent"].ToString() + "%";
                ddlEditNCB.Text = _dtSelect.Rows[0]["NCDPercent"].ToString() == "-1" ? "0" : _dtSelect.Rows[0]["NCDPercent"].ToString();

                lblCTPL.Text = Convert.ToBoolean(_dtSelect.Rows[0]["IsCTPL"]) == true ? "ใช่" : "ไม่ต้องการ";
                _IsClaim = Convert.ToBoolean(_dtSelect.Rows[0]["IsClaimLastYear"].ToString());
                _IsAddDriver = Convert.ToBoolean(_dtSelect.Rows[0]["IsAddDriver"].ToString());
                string _coverCommDate = _dtSelect.Rows[0]["CoverageCommenceDate"].ToString();

                if (DateTime.TryParse(_coverCommDate, out _dtCoverCommDate))
                {
                    lblCoverCommencementDate.Text = _dtCoverCommDate.ToString("dd/MMM/yyyy");
                    if (DateTime.Compare(dateTimeNow, _dtCoverCommDate) > 0)
                    {
                        lblCommenceDateStatus.Text = "0";
                        lblCommenceDateStatusMessage.Text = Resources.General.CommencementOVER;
                        lblCommenceDateStatusMessage.Font.Bold = true;
                        lblCommenceDateStatusMessage.ForeColor = System.Drawing.Color.Red;

                        ListItem myItem = new ListItem(lblCoverCommencementDate.Text, lblCoverCommencementDate.Text);
                        ddlEditCoverCommencementDate.Items.Insert(0, myItem);
                        ddlEditCoverCommencementDate.Items[0].Attributes.Add("style", "color:red;");

                        lblEditCoverCommencementDateCaption.Font.Bold = true;
                        lblEditCoverCommencementDateCaption.ForeColor = System.Drawing.Color.Red;
                        ClientScript.RegisterStartupScript(this.GetType(), "JS_ClosedCallAlert", "alert('" + Resources.General.CommencementCheck + "');", true);
                        lblEditCoverCommencementDateMessage.Text = Resources.General.CommencementCheck;
                    }
                    else
                    {
                        lblCommenceDateStatus.Text = "1";
                        lblCommenceDateStatusMessage.Text = Resources.General.CommencementOK;
                        lblCommenceDateStatusMessage.Font.Bold = true;
                        lblCommenceDateStatusMessage.ForeColor = System.Drawing.Color.Green;
                    }

                    ddlEditCoverCommencementDate.Text = lblCoverCommencementDate.Text;
                    lblEditCoverCommencementDate.Text = lblCoverCommencementDate.Text;
                }
                else
                {
                    lblCommenceDateStatus.Text = "0";
                    lblCommenceDateStatusMessage.Text = Resources.General.CommencementNOTVALID;
                    lblCommenceDateStatusMessage.Font.Bold = true;
                    lblCommenceDateStatusMessage.ForeColor = System.Drawing.Color.Red;
                }

                CheckQuoteStatus();

                if (_IsAddDriver == true)
                {
                    lblDriverCount.Text = _dtSelect.Rows[0]["NoOfDriver"].ToString();
                    ddlEditNamedDriver.Text = lblDriverCount.Text;
                    chkNamedDriver.Checked = true;
                }
                else
                {
                    lblDriverCount.Text = "0";
                    ddlEditNamedDriver.Text = "0";
                    chkNamedDriver.Checked = false;
                }

                lblClaimInfo.Text = _IsClaim == true ? "ใช่" : "ไม่มี";

                _dtSelect = null;
                _dtSelect = new DataTable("dtSelect");

                _strSelect = " Select CD.MakeModelDesc, CD.ManufactYear, CD.Info15, CD.Info16, CD.Info17, CD.Info18, CD.Info19, P.TH CurrentInsurer "
                            + " from tblFleetCarDetail CD"
                            + " INNER JOIN tblPreInsurer P ON CAST(CD.Info1 AS INT) = P.PreInsurerId"
                            + " Where P.CompanyType = 1 And P.ServiceType = 100 AND CD.CompanyId = " + txtCompanyId.Text + " And CD.FleetCarId= " + txtFleetCarId.Text;
                _dtSelect = _db.GetDataTable(_strSelect);
                if (_dtSelect != null && _dtSelect.Rows.Count > 0)
                {
                    lblCarMakeModel.Text = _dtSelect.Rows[0]["MakeModelDesc"].ToString();
                    lblRegYear.Text = _dtSelect.Rows[0]["ManufactYear"].ToString();
                    lblCurrentInsurer.Text = _dtSelect.Rows[0]["CurrentInsurer"].ToString();
                    txtEditLicensePlate.Text = "";
                    lblEditLicensePlate.Text = "";
                    if (_dtSelect.Rows[0]["Info15"] != DBNull.Value && _dtSelect.Rows[0]["Info15"].ToString() != string.Empty)
                    {
                        txtEditLicensePlate.Text = _dtSelect.Rows[0]["Info15"].ToString();
                        lblEditLicensePlate.Text = _dtSelect.Rows[0]["Info15"].ToString();
                    }

                    if (_dtSelect.Rows[0]["Info16"] != DBNull.Value && _dtSelect.Rows[0]["Info16"].ToString() != string.Empty)
                    {
                        ddlEditNCB.Text = _dtSelect.Rows[0]["Info16"].ToString();
                    }

                    if (_dtSelect.Rows[0]["Info17"] != DBNull.Value && _dtSelect.Rows[0]["Info17"].ToString() != string.Empty)
                    {
                        ddlEditNamedDriver.Text = _dtSelect.Rows[0]["Info17"].ToString();
                    }

                    if (_dtSelect.Rows[0]["Info19"] != DBNull.Value && _dtSelect.Rows[0]["Info19"].ToString() != string.Empty)
                    {
                        ddlEditCoverCommencementDate.Text = _dtSelect.Rows[0]["Info19"].ToString();
                        lblEditCoverCommencementDate.Text = _dtSelect.Rows[0]["Info19"].ToString();
                    }
                }

                divCustomerPolicyDetail.Visible = true;
            }



            _dtSelect = null;
            _dtSelect = new DataTable("dtSelect");

            _db = null;
            _dtSelect = null;
            #endregion

            #region Show Hide Links
            if (divCompletedQuoteDetails.Visible == false)
            {
                divEditDetail.Visible = true;
                divPremiumList.Visible = true;
                divLinks.Visible = true;

            }
            else
            {
                divLinks.Visible = true;

                divEditDetail.Visible = true;
                divPremiumList.Visible = true;

            }
            #endregion

            #region Broker Premium
            grvQuoteList.DataBind();
            grvPremiumList.DataBind();
            if (grvPremiumList.Rows.Count > 0)
            {
                string url = "PremiumDownload.aspx?carid=" + txtCarId.Text.ToString();
                hplPremiumDownLoad.NavigateUrl = url;
            }
            else
            {
                hplPremiumDownLoad.Visible = false;
                hplPremiumDownLoad.NavigateUrl = "";
            }

            divCXBrokerPremium.Visible = true;
            #endregion

            CheckApplicationStatus();


        }
    }

    private void ShowBrokerPremiumDetail(FleetBrokerPremium _fleetbrokerPremium, bool bLoadForRenewal)
    {
        txtPremiumId.Text = _fleetbrokerPremium.FleetBrokerPremiumId.ToString();
        if (txtGG.Text.Trim() == "GGSPECIAL")
        {
            DataTable _dtBrokerProvider = General.GetComboItem("BrokerProvider", "CXBrokerProviderId", _fleetbrokerPremium.CXBrokerProviderId.ToString(), true);
            if (_dtBrokerProvider != null && _dtBrokerProvider.Rows.Count > 0)
            {
                ddlBrokerProvider.Items.Clear();
                ddlBrokerProvider.DataSource = _dtBrokerProvider;
                ddlBrokerProvider.DataTextField = _dtBrokerProvider.Columns[0].ColumnName.ToString();
                ddlBrokerProvider.DataValueField = _dtBrokerProvider.Columns[1].ColumnName.ToString();
                ddlBrokerProvider.DataBind();
                ddlBrokerProvider.Items.Insert(0, new ListItem("Select", "-1"));
            }
        }
        
        ddlBrokerProvider.SelectedIndex = ddlBrokerProvider.Items.IndexOf(ddlBrokerProvider.Items.FindByValue(_fleetbrokerPremium.CXBrokerProviderId.ToString()));
        ddlBrokerProvider_SelectedIndexChanged(null, null);
        ddlBrokerCoverType.Text = _fleetbrokerPremium.ProviderCoverTypeId.ToString();
        ddlBrokerCoverType_SelectedIndexChanged(null, null);
        txtNetPremium.Text = _fleetbrokerPremium.Premium.ToString();

        if (txtGG.Text.Trim() == "GGSPECIAL")
        {
            ddlDiscountPercentage.Items.Clear();
            ddlDiscountPercentage.Items.Add(new ListItem("18 %", "18"));
            ddlDiscountPercentage.Items.Add(new ListItem("0 %", "0"));
            ddlDiscountPercentage.Text = "18";
        }
        else if (_fleetbrokerPremium.DiscountPercentage >= 5 && bLoadForRenewal == false) //Sakthi on 29 Apr 2013 if (_brokerPremium.DiscountPercentage > 5 && bLoadForRenewal == false)
        {
            ddlDiscountPercentage.Items.Clear();
            for (int p = _fleetbrokerPremium.DiscountPercentage; p >= 0; p--)
            {
                ddlDiscountPercentage.Items.Add(new ListItem(p.ToString() + " " + "%", p.ToString()));
            }
            
            if (lblRenewalStaus.Text != string.Empty && lblRenewalStaus.Text != "0")
            {
                ddlDiscountPercentage.Items.Clear();
                for (int r = 7; r >= 0; r--)
                {
                    ddlDiscountPercentage.Items.Add(new ListItem(r.ToString() + " " + "%", r.ToString()));
                }
            }            
        }

        chkSelected.Checked = _fleetbrokerPremium.SelectedStatus;
        ddlGarageType.Text = _fleetbrokerPremium.WorkShop;
        txtDeductible.Text = _fleetbrokerPremium.DEC;
        txtFireTheft.Text = _fleetbrokerPremium.FireTheft;
        txtOwnDamage.Text = _fleetbrokerPremium.OwnDamage;
        chkCTPL.Checked = _fleetbrokerPremium.IsIncludeCMI;
        chkCTPL_CheckedChanged(null, null);
        txtTPPD.Text = _fleetbrokerPremium.TPPD;
        txtTPBIA.Text = _fleetbrokerPremium.TPBIA;
        txtTPBIP.Text = _fleetbrokerPremium.TPBIP;
        txtBailBond.Text = _fleetbrokerPremium.BailBound;
        txtNetPremium.Text = _fleetbrokerPremium.Premium.ToString();
        txtGrossPremium.Text = _fleetbrokerPremium.TotalVMI.ToString();
        if (_fleetbrokerPremium.Info3 != string.Empty)
        {
            ddlVehicleBodyType.Text = _fleetbrokerPremium.Info3;
            ddlVehicleBodyType_SelectedIndexChanged(null, null);
            txtCTPL.Text = _fleetbrokerPremium.TotalCMI.ToString();
        }

        if (_fleetbrokerPremium.Info4 == "1")
        {
            chkCompanyStaff.Checked = true;
        }
        else
        {
            chkCompanyStaff.Checked = false;
        }

        txtFloodCoverAmount.Text = _fleetbrokerPremium.Info5;

        if (_fleetbrokerPremium.Info6 == "1")
        {
            chkNamedDriver.Checked = true;
        }
        else
        {
            chkNamedDriver.Checked = false;
        }

        txtAccModCost.Text = _fleetbrokerPremium.Info7;

        if (lblRenewalStaus.Text != string.Empty && lblRenewalStaus.Text != "0" && bLoadForRenewal == false)
        {
            if (_fleetbrokerPremium.DiscountPercentage > 7)
            {
                ddlDiscountPercentage.Text = "7";
            }
            else
            {
                ddlDiscountPercentage.Text = _fleetbrokerPremium.DiscountPercentage.ToString();
            }
        }
        else
        {
            ddlDiscountPercentage.Text = _fleetbrokerPremium.DiscountPercentage.ToString();
        }
        
        ddlDiscountPercentage_SelectedIndexChanged(null, null);
        txtFinalAnnualPremium.Text = _fleetbrokerPremium.FinalAnnualPremium.ToString("#0.00");
        txtFinalAnnualPremiumNoDisc.Text = _fleetbrokerPremium.FinalAnnualPremiumNoDisc.ToString("#0.00");
        txtPA.Text = _fleetbrokerPremium.PADriver.ToString();
        txtMED.Text = _fleetbrokerPremium.MedicalExpense.ToString();
        txtEditLicensePlate.Text = _fleetbrokerPremium.Info2;
        lblEditLicensePlate.Text = _fleetbrokerPremium.Info2;
        txtPremiumChangeComments.Text = _fleetbrokerPremium.Info8;

        if (_fleetbrokerPremium.Bank != string.Empty && _fleetbrokerPremium.Bank != "-1")
        {
            ddlCreditCard.Text = _fleetbrokerPremium.Bank;
        }

        if (_fleetbrokerPremium.NoofInstallment > 2)
        {            
            ddlNoofInstallments.Items.Clear();
            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
            ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
            ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
            ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));

            ddlNoofInstallments.Text = _fleetbrokerPremium.NoofInstallment.ToString();
        }
        ddlCreditCard_SelectedIndexChanged(null, null);
        ddlNoofInstallments_SelectedIndexChanged(null, null);
        if (_fleetbrokerPremium.PaymentOption != string.Empty && _fleetbrokerPremium.PaymentOption != "-1")
        {
            ddlPaymentOption.Text = _fleetbrokerPremium.PaymentOption;
        }
        lblB4EditFinalAnnualPremium.Text = _fleetbrokerPremium.OriginalPremiumWD.ToString("#0.00");
        lblB4EditFinalAnnualPremiumNoDisc.Text = _fleetbrokerPremium.OriginalPremiumWOD.ToString("#0.00");
        if (txtTescoAmount.Text.Trim() != "0" && txtTescoAmount.Text.Trim() != "0.00")
        {
            
        }
    }

    private void ClearFields()
    {
        txtPremiumId.Text = "0";
        txtNetPremium.Text = "";

        ddlDiscountPercentage.Items.Clear();
        ddlDiscountPercentage.Items.Add(new ListItem("0 %", "0"));
        ddlDiscountPercentage.Text = "0";
        //txtPremiumPackage.Text = "";
        ddlGarageType.Text = "-1";
        chkSelected.Checked = false;

        txtDeductible.Text = "";
       

        txtFireTheft.Text = "";
        //txtOwnDamage.Text = "";
        chkCTPL.Checked = true;
        txtCTPL.Enabled = true;
        chkChangePremium.Checked = false;

        txtTPPD.Text = "";
        txtTPBIA.Text = "";
        txtTPBIP.Text = "";
        txtPA.Text = "";
        txtMED.Text = "";
        txtBailBond.Text = "";

        lblTax.Text = "0";
        lblVAT.Text = "0";
        lblDiscountAmount.Text = "0";
        lblAnnualPremium.Text = "0";
        lblNetPremium.Text = "0";
        txtGrossPremium.Text = "0";
        txtFinalAnnualPremium.Text = "0";
        txtFinalAnnualPremiumNoDisc.Text = "0";
        txtFinalAnnualPremium.ReadOnly = true;
        txtFinalAnnualPremiumNoDisc.ReadOnly = true;

        txtFloodCoverAmount.Text = "0";
        txtAccModCost.Text = "0";
        txtPremiumChangeComments.Text = string.Empty;

        //Monthly Installment -- Start
        lblTotalGrossPremiumWD.Text = "0";
        lblFirstInstallmentWD.Text = "0";
        lblLastInstallmentWD.Text = "0";
        lblTotalGrossPremiumWOD.Text = "0";
        lblFirstInstallmentWOD.Text = "0";
        lblLastInstallmentWOD.Text = "0";
        lblFirstInstallmentWDdesc.Text = string.Empty;
        lblFirstInstallmentWODdesc.Text = string.Empty;

        ddlNoofInstallments.Items.Clear();
        ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));

        ddlCreditCard.Items.Clear();
        ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));

        ddlGGDiscount.Items.Clear();
        ddlGGDiscount.Items.Add(new ListItem("0 %", "0"));

        //Monthly Installment -- End
    }

    private void ShowTescoAmount()
    {
        lblTesco.Text = "";
        string _strSelect = "";
        string strCommence = "";
        string minPremium = "0";
        string strctpl = "0";
        decimal _Premium = 0;
        decimal _ctpl = 0;
        MyDatabase _db = new MyDatabase();
        DataTable dt = new DataTable();
        DataTable _dtSelect = new DataTable();
        DateTime _CoverCommDate = dateTimeNow;
        DateTime _CurrentDate = dateTimeNow;
        TimeSpan ts;
        Int32 days = 0;
        minPremium = txtFinalAnnualPremium.Text;
        if (!decimal.TryParse(minPremium, out _Premium))
        {
            _Premium = 0;
        }
        if (chkCTPL.Checked)
        {
            strctpl = txtCTPL.Text;
        }
        if (!decimal.TryParse(strctpl, out _ctpl))
        {
            _ctpl = 0;
        }
        if (lblRenewalStaus.Text.Trim() != string.Empty && (lblRenewalStaus.Text.Trim() == "1" || lblRenewalStaus.Text.Trim() == "2"))
        {
            txtTescoAmount.Text = "0";
        }
        else
        {
            _strSelect = @" SELECT CoverageCommenceDate = CASE WHEN LEN(CD.Info19) > 0 THEN CD.Info19 ELSE CP.CoverageCommenceDate END ";
            _strSelect += " FROM tblFleetCarPolicy CP INNER JOIN tblFleetCarDetail CD ON CD.FleetCarId = CP.FleetCarId ";
            _strSelect += " WHERE CP.FleetCarId = " + txtFleetCarId.Text;
            _dtSelect = _db.GetDataTable(_strSelect);
            if (_dtSelect != null && _dtSelect.Rows.Count > 0)
            {
                strCommence = _dtSelect.Rows[0]["CoverageCommenceDate"].ToString();
            }
            if (!DateTime.TryParse(strCommence, out _CoverCommDate))
            {
                _CoverCommDate = new DateTime();
            }
            ts = (_CoverCommDate.Date - _CurrentDate.Date);
            days = ts.Days;
            txtTescoAmount.Text = "0";
            if (_Premium > 0 && _Premium <= 12000)
            {
                if (days > 60)
                {
                    txtTescoAmount.Text = "200";
                }
            }
            else if (_Premium > 12000 && _Premium <= 15000)
            {
                if (days >= 15 && days <= 30)
                {
                    txtTescoAmount.Text = "200";
                }
                else if (days > 30 && days <= 60)
                {
                    txtTescoAmount.Text = "300";
                }
                else if (days > 60)
                {
                    txtTescoAmount.Text = "400";
                }
            }
            else if (_Premium > 15000 && _Premium <= 20000)
            {
                if (days >= 15 && days <= 30)
                {
                    txtTescoAmount.Text = "300";
                }
                else if (days > 30 && days <= 60)
                {
                    txtTescoAmount.Text = "400";
                }
                else if (days > 60)
                {
                    txtTescoAmount.Text = "600";
                }
            }
            else if (_Premium > 20000 && _Premium <= 30000)
            {
                if (days >= 15 && days <= 30)
                {
                    txtTescoAmount.Text = "400";
                }
                else if (days > 30 && days <= 60)
                {
                    txtTescoAmount.Text = "500";
                }
                else if (days > 60)
                {
                    txtTescoAmount.Text = "700";
                }
            }
            else if (_Premium > 30000 && _Premium <= 40000)
            {
                if (days >= 15 && days <= 30)
                {
                    txtTescoAmount.Text = "500";
                }
                else if (days > 30 && days <= 60)
                {
                    txtTescoAmount.Text = "600";
                }
                else if (days > 60)
                {
                    txtTescoAmount.Text = "800";
                }
            }
            else if (_Premium > 40000)
            {
                if (days >= 15 && days <= 30)
                {
                    txtTescoAmount.Text = "600";
                }
                else if (days > 30 && days <= 60)
                {
                    txtTescoAmount.Text = "700";
                }
                else if (days > 60)
                {
                    txtTescoAmount.Text = "1000";
                }
            }
        }
    }

    private void LoadBrokerProvider()
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";
        DataTable _dtBrokerProvider = General.GetComboItem("BrokerProvider", true);
        if (_dtBrokerProvider != null && _dtBrokerProvider.Rows.Count > 0)
        {
            ddlBrokerProvider.DataSource = _dtBrokerProvider;
            ddlBrokerProvider.DataTextField = _dtBrokerProvider.Columns[0].ColumnName.ToString();
            ddlBrokerProvider.DataValueField = _dtBrokerProvider.Columns[1].ColumnName.ToString();
            ddlBrokerProvider.DataBind();
        }

        ddlBrokerProvider.Items.Insert(0, new ListItem("Select", "-1"));
      
    }

    private void LoadBrokerCoverType()
    {
        lblPremiumError.Text = "";
        lblPremiumMessage.Text = "";
        ddlBrokerCoverType.Items.Clear();
        MyDatabase _db = new MyDatabase();
        DataTable _dtBrokerCoverType = new DataTable("tblBrokerCoverType");
        _dtBrokerCoverType = _db.GetDataTable("Select ProviderCoverTypeID, " + Resources.DBTable.FieldName + " FROM tblCXBrokerProviderCoverType WHERE Status = 1 ORDER BY ProviderCoverTypeID");
        if (ddlBrokerProvider.Text == "41" && txtUserTypeId.Text == "1001")
        {
            _dtBrokerCoverType = _db.GetDataTable("Select ProviderCoverTypeID, " + Resources.DBTable.FieldName + " FROM tblCXBrokerProviderCoverType WHERE Status = 1 AND ProviderCoverTypeID<> 11 ORDER BY ProviderCoverTypeID");
        }
        if (_dtBrokerCoverType != null && _dtBrokerCoverType.Rows.Count > 0)
        {
            ddlBrokerCoverType.DataSource = _dtBrokerCoverType;
            ddlBrokerCoverType.DataTextField = _dtBrokerCoverType.Columns[1].ColumnName.ToString();
            ddlBrokerCoverType.DataValueField = _dtBrokerCoverType.Columns[0].ColumnName.ToString();
            ddlBrokerCoverType.DataBind();
        }
        ddlBrokerCoverType.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    public void GeneratePremium(Int64 CECarId)
    {

        Int32 _Count = 0;
        Label lblContent = new Label();
        string _html = "";
        string _fileName = "FileName";
        _fileName = "Premium_" + CECarId;
        string _UserCover = "";

        string _ProductType = "CIN";
        DataSet _dsPremium = new DataSet();
        BrokerPremiumDB _prokerpremiumdb = new BrokerPremiumDB();
        _dsPremium = _prokerpremiumdb.GetBrokerPremium(CECarId, _ProductType, Convert.ToInt16(lblLangOption.Text));
        if (_dsPremium.Tables[0].Rows.Count > 0)
        {
            if (_dsPremium.Tables.Count > 1)
            {
                if (_dsPremium.Tables[1].Rows.Count > 0)
                {
                    _UserCover = _dsPremium.Tables[1].Rows[0]["ProviderCoverTypeDesc"].ToString();
                }
            }

            _Count = _dsPremium.Tables[0].Rows.Count;
            if (_Count > 4)
            {
                _Count = 4;
            }

            #region variables
            string[] _Insurer = new string[_Count];
            string[] _Workshop = new string[_Count];
            string[] _Premium = new string[_Count];
            string[] _Excess = new string[_Count];
            string[] _QuoteId = new string[_Count];
            string[] _Cover = new string[_Count];
            string[] _Package = new string[_Count];
            #endregion

            for (int i = 0; i < _Count; i++)
            {
                #region Values assign to variables
                _Insurer[i] = _dsPremium.Tables[0].Rows[i]["CompanyName"].ToString();
                _Workshop[i] = _dsPremium.Tables[0].Rows[i]["WorkShop"].ToString();
                _Premium[i] = "$" + _dsPremium.Tables[0].Rows[i]["Premium"].ToString();
                _Excess[i] = "$" + _dsPremium.Tables[0].Rows[i]["Excess"].ToString();
                _QuoteId[i] = CECarId.ToString();
                _Cover[i] = _dsPremium.Tables[0].Rows[i]["ProviderCoverTypeDesc"].ToString();
                _Package[i] = _dsPremium.Tables[0].Rows[i]["Package"].ToString();
                #endregion
            }

            #region Html

            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());
            string domainUrl = "";
            string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXCINMIsCXLive");
            if (_strCXLive == "2")
            {
                domainUrl = "http://" + myUri.Authority;
            }
            else
            {
                domainUrl = "http://" + myUri.Host;
            }
            string imgUrl = domainUrl + "/CX_Broker/images/header/kim_banner.png";

            _html = "<table style='width: 100%; background-color: white;' cellpadding='0' cellspacing='0'>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'><img src='" + imgUrl + "' alt='KIM Brokers' /></td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'>&nbsp;</td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'>Below are the instant competitive quotations sourced from some insurers.</td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'>&nbsp;</td>"
                    + "</tr>"

                    + "<tr>"
                //+ "<td align='left' style='width:100%'>Vehicle Number: " + txtVehicleNumber.Text + "</td>"
                    + "<td align='left' style='width:100%'>Vehicle Number: " + "N/A" + "</td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'>Type of Cover: " + _UserCover.ToString() + "</td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'>&nbsp;</td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'><b>QUOTES</b></td>"
                    + "</tr>"

                    + "<tr>"
                    + "<td align='left' style='width:100%'>"
                    + "<table style='width: 100%; background-color: white;' cellpadding='5' cellspacing='2' border='1'>"
                    + "<tr>"
                    + "<td align='left' style='width:150px'>&nbsp;</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px'>Quotation " + j + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Quote ID</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px'> " + _QuoteId[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Insurer</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px'> " + _Insurer[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Restriction on Workshop</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px'> " + _Workshop[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Cover Type</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px'> " + _Cover[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Package</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px'> " + _Package[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Premium</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px; color:blue; font-weight:bold;'> " + _Premium[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"

            + "<tr>"
            + "<td align='left' style='width:150px'>Excess (Insured + Named Drivers)</td>";
            for (int j = 1; j <= _Count; j++)
            {
                _html += "<td align='center' style='width:250px; color:blue; font-weight:bold;'> " + _Excess[j - 1].ToString() + "</td>";
            }
            _html += "</tr>"
            + "</table>"
            + "</td>"
            + "</tr>"

            + "<tr>"
            + "<td align='left' style='width:100%'>&nbsp;</td>"
            + "</tr>"

            + "<tr>"
            + "<td align='left' style='width:100%'>&bull; This Quote Is Subject To the Insurer's Final Confirmation And Coverage Is Only Effective When The Insurer Has Accepted The Risk</td>"
            + "</tr>"

            + "<tr>"
            + "<td align='left' style='width:100%'>&bull; The Insurer Reserves The Right To Revise or Withdraw The Quote If Any Of the Information Given Differs From The Actual Risk</td>"
            + "</tr>"

            + "<tr>"
            + "<td align='left' style='width:100%'>&bull; Unless Otherwise Specified, The Quote Is Valid Only For 14 Days From The Date Of Quote</td>"
            + "</tr>"

            + "<tr>"
            + "<td align='left' style='width:100%'>&bull; All premiums quoted are nett, ie where applicable, inclusive of NCD, Safe Driver Discount and prevailing GST</td>"
            + "</tr>"

            + "</table>";
            #endregion

            string _HeaderText = "";

            Label lblPremiumHtml = new Label();
            lblPremiumHtml.Text = _html;
            ExportHtml(_fileName, lblPremiumHtml, _HeaderText);
        }
    }

    public void ExportHtml(string fileName, Label lblPremiumHtml, string headerText)
    {
        string attachment = "attachment; filename=" + fileName + ".htm";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "text/HTML";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        frm.InnerHtml = headerText;
        lblPremiumHtml.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(lblPremiumHtml);
        frm.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();

        
    }

    private void CheckQuoteStatus()
    {
        lblCommenceDateStatusMessage.Visible = false;
        lblQuoteDateTimeStatusMessage.Visible = false;

        if (lblCommenceDateStatus.Text == "0" && lblQuoteDateTimeStatus.Text == "1")
        {
            lblQuoteStatusMessage.Text = lblCommenceDateStatusMessage.Text;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Red;
        }
        else if (lblQuoteDateTimeStatus.Text == "0" && lblCommenceDateStatus.Text == "1")
        {
            lblQuoteStatusMessage.Text = lblQuoteDateTimeStatusMessage.Text;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Red;
        }
        else if (lblQuoteDateTimeStatus.Text == "0" && lblCommenceDateStatus.Text == "0")
        {
            lblQuoteDateTimeStatusMessage.Visible = false;
            lblCommenceDateStatusMessage.Visible = false;
            lblQuoteStatusMessage.Text = Resources.General.CommencementOVER;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            lblQuoteDateTimeStatusMessage.Visible = false;
            lblCommenceDateStatusMessage.Visible = false;
            lblQuoteStatusMessage.Text = Resources.General.EverythingOK;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Green;
        }

        divBuyNowStatusMessage.Visible = true;
    }

    private void CheckApplicationStatus()
    {
        MyDatabase _db = new MyDatabase();
        SortedList _paraList = new SortedList();
        _paraList.Add("@FleetCarId", txtFleetCarId.Text);
        _paraList.Add("@CompanyId", txtCompanyId.Text);
        DataTable _dtApp = new DataTable("tblApp");
        _dtApp = _db.GetDataTableBySP("sprocFleetApplicationStatusSelectItem", _paraList);

        if (_dtApp != null && _dtApp.Rows.Count > 0)
        {
            lblCarMoreDetailID.Text = _dtApp.Rows[0]["FleetCarMoreDetailId"].ToString();
            lblAppStatus.Text = string.Empty;

            lblAppStatusMessage.Text = string.Empty;
            lblAppStatusMessage.Text = Resources.General.NonGGFoundAppDetailSubmission;
            lblAppStatusMessage.ForeColor = System.Drawing.Color.Red;
            lblAppStatusMessage.Font.Bold = true;

            ddlBrokerProvider.Text = _dtApp.Rows[0]["ProviderCompanyId"].ToString();
            ddlBrokerProvider_SelectedIndexChanged(null, null);
            ddlBrokerCoverType.Text = _dtApp.Rows[0]["InsuranceType"].ToString();
            ddlBrokerCoverType_SelectedIndexChanged(null, null);

            ddlBrokerCoverType.Enabled = false;
            ddlBrokerProvider.Enabled = false;
            chkCTPL.Enabled = false;
            txtCTPL.Enabled = false;
            txtGrossPremium.Enabled = false;
            txtFinalAnnualPremium.Enabled = false;

            txtEditLicensePlate.Enabled = false;
            ddlEditNCB.Enabled = false;
            ddlEditNamedDriver.Enabled = false;

            ddlGarageType.Enabled = false;
            chkSelected.Enabled = false;
            SetGVPremiumSelectedIndex();

            lblCarMoreDetailID.Visible = false;
            lblAppStatus.Visible = false;
            btnSubmitPremium.Enabled = false;
            btnEditSubmit.Enabled = false;
        }
        else
        {
            SetGVPremiumSelectedIndex();
            ddlBrokerCoverType.Enabled = true;
            ddlBrokerProvider.Enabled = true;
            chkCTPL.Enabled = true;
            txtCTPL.Enabled = true;
            txtGrossPremium.Enabled = true;
            txtFinalAnnualPremium.Enabled = true;
            ddlDiscountPercentage.Enabled = true;

            txtEditLicensePlate.Enabled = true;
            ddlEditNCB.Enabled = true;
            ddlEditNamedDriver.Enabled = true;

            ddlGarageType.Enabled = true;
            chkSelected.Enabled = true;
            lblCarMoreDetailID.Text = "-1";
            lblAppStatus.Text = string.Empty;
            btnSubmitPremium.Enabled = true;
            btnEditSubmit.Enabled = true;
            lblAppStatusMessage.Text = string.Empty;
            if (grvPremiumList.Rows.Count > 0)
            {
                lblAppStatusMessage.Text = "( " + grvPremiumList.Rows.Count.ToString() + " ) record(s) found.";
            }
            else
            {
                lblAppStatusMessage.Text = "No records found.";
            }

            lblAppStatusMessage.ForeColor = System.Drawing.Color.Red;
            lblAppStatusMessage.Font.Bold = true;

        }
    }

    private void SetGVPremiumSelectedIndex()
    {
        foreach (GridViewRow myRow in grvPremiumList.Rows)
        {
            string _selectStatus = myRow.Cells[13].Text.ToString().ToLower();
            if (_selectStatus == "yes")
            {
                grvPremiumList.SelectedIndex = myRow.RowIndex;
                myRow.Cells[10].ForeColor = System.Drawing.Color.Red;
                lblSelectedRefNo.Text = myRow.Cells[5].Text.ToString();
                break;
            }
            else
            {
            }
        }
    }

    private void ShowQuoteStatusAlert()
    {
        if (lblCommenceDateStatus.Text == "0" || lblQuoteDateTimeStatus.Text == "0")
        {
           ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + lblQuoteStatusMessage.Text + "');", true);
        }
    }

    private void LoadDiscountPercentageList()
    {
        //31	Chartis
        //46	Tokio Marine
        //41	Kurnia
        //35	KrungThai
        //33	MuangThai
        //32	BKI
        //29	LMG  Insurance
        //12	MSIG
        //11	Allianz CP
        //16	AXA

        DateTime _dtCoverCommDate = dateTimeNow;
        if (lblCoverCommencementDate.Text != string.Empty)
        {
            _dtCoverCommDate = Convert.ToDateTime(lblCoverCommencementDate.Text);
        }
        DateTime _dtThreeDayPlus = Convert.ToDateTime(dateTimeNow.AddDays(3).ToString("dd/MMM/yyyy"));
        DateTime _dtEditCoverCommDate = Convert.ToDateTime(lblEditCoverCommencementDate.Text);

        int _maxPercentage = 0;
        int _providerComId = Convert.ToInt32(ddlBrokerProvider.Text);

        //              ≤ 3 days	≥ 4 days
        // 16     AXA	    2%	        7%
        // 11     AZCP	    2%	        7%
        // 32     BKI	    2%	        7%
        // 31     CHARTIS	4%	        13%
        // 41     KURNIA	4%	        13%
        // 29     LMG	    4%	        11%
        // 12     MSIG	    4%	        13%
        // 33     MTI	    2%	        8%
        // 46     TOKIO	    2%	        5%
        if (_providerComId == 41 || divCompletedQuoteDetails.Visible == false)
        {
            if (DateTime.Compare(_dtThreeDayPlus, _dtEditCoverCommDate) > 0)
            {
                if (_providerComId == 16) //AXA
                {
                    _maxPercentage = 2;
                }
                else if (_providerComId == 11) // AZCP
                {
                    _maxPercentage = 2;
                }
                else if (_providerComId == 32) //BKI
                {
                    _maxPercentage = 2;
                }
                else if (_providerComId == 31) //CHARTIS
                {
                    _maxPercentage = 4;
                }
                else if (_providerComId == 41) //KURNIA
                {
                    _maxPercentage = 4;
                }
                else if (_providerComId == 29) //LMG
                {
                    _maxPercentage = 4;
                }
                else if (_providerComId == 12) //MSIG
                {
                    _maxPercentage = 4;
                }
                else if (_providerComId == 33) //MTI
                {
                    _maxPercentage = 2;
                }
                else if (_providerComId == 35) //KPI
                {
                    _maxPercentage = 2;
                }
                else if (_providerComId == 46) //TOKIO
                {
                    _maxPercentage = 2;
                }
            }
            else
            {
                if (_providerComId == 16) //AXA
                {
                    _maxPercentage = 7;
                }
                else if (_providerComId == 11) // AZCP
                {
                    _maxPercentage = 7;
                }
                else if (_providerComId == 32) //BKI
                {
                    _maxPercentage = 7;
                }
                else if (_providerComId == 31) //CHARTIS
                {
                    _maxPercentage = 13;
                }
                else if (_providerComId == 41) //KURNIA
                {
                    _maxPercentage = 13;
                }
                else if (_providerComId == 29) //LMG
                {
                    _maxPercentage = 11;
                }
                else if (_providerComId == 12) //MSIG
                {
                    _maxPercentage = 13;
                }
                else if (_providerComId == 33) //MTI
                {
                    _maxPercentage = 8;
                }
                else if (_providerComId == 35) //KPI
                {
                    _maxPercentage = 10;
                }
                else if (_providerComId == 46) //TOKIO
                {
                    _maxPercentage = 5;
                }
            }
        }
        else
        {
            _maxPercentage = 10;
        }

        DateTime _dtStartDate = new DateTime(2012, 09, 01);
        DateTime _dtEndDate = new DateTime(2099, 12, 31);
        if (DateTime.Compare(dateTimeNow, _dtStartDate) > 0 && DateTime.Compare(dateTimeNow, _dtEndDate) < 0)
        {
            _maxPercentage = 5;
            if (Session[General.UserCampaign] != null && Session[General.UserCampaign].ToString() == "1001")
            {
                _maxPercentage = 9;
            }

            if (chkCompanyStaff.Checked)
            {
                _maxPercentage = 15;
            }

            if (_providerComId == 41 || _providerComId == 43)
            {
                ddlDiscountPercentage.Enabled = true;
            }
            else
            {
            }
            Int64 _PremiumId = 0;
            if (!Int64.TryParse(txtPremiumId.Text, out _PremiumId))
            {
                _PremiumId = 0;
            }

            if (_PremiumId > 0)
            {
                Int32 percert = _maxPercentage;
                DataSet _dsPremium = new DataSet();
                _dsPremium = GetBrokerPremiumbyPremiumId(_PremiumId);
                if (_dsPremium != null && _dsPremium.Tables.Count > 0 && _dsPremium.Tables[0].Rows.Count > 0)
                {
                    if (_dsPremium.Tables[0].Rows[0]["DiscountPercentage"] != DBNull.Value)
                    {
                        Int32.TryParse(_dsPremium.Tables[0].Rows[0]["DiscountPercentage"].ToString(), out percert);
                        if (percert > 0)
                        {
                            _maxPercentage = percert;
                        }
                    }
                }
            }
            if (lblRenewalStaus.Text == "1" || lblRenewalStaus.Text == "2")
            {
                _maxPercentage = 7;
            }

            if (txtGG.Text.Trim() == "GGSPECIAL")
            {
                _maxPercentage = 18;
            }

            if (chkCompanyStaff.Checked)
            {
                _maxPercentage = 15;
            }
        }

        if (_providerComId == 41 && ddlBrokerCoverType.Text == "11")
        {
            _maxPercentage = 0;
        }
        if (_providerComId == 39)
        {
            _maxPercentage = 0;
        }
        ddlDiscountPercentage.Items.Clear();

        for (int i = _maxPercentage; i >= 0; i--)
        {
            ddlDiscountPercentage.Items.Add(new ListItem(i.ToString() + " " + "%", i.ToString()));
        }
        if (txtGG.Text.Trim() == "GGSPECIAL")
        {
            ddlDiscountPercentage.Items.Clear();
            ddlDiscountPercentage.Items.Add(new ListItem(_maxPercentage.ToString() + " " + "%", _maxPercentage.ToString()));
            ddlDiscountPercentage.Items.Add(new ListItem("0 %", "0"));
            ddlDiscountPercentage.Text = _maxPercentage.ToString();
            ddlDiscountPercentage.Enabled = false;
        }
        if (divCompletedQuoteDetails.Visible)
        {
            ddlDiscountPercentage.Text = _maxPercentage.ToString();
        }

        if (DateTime.Compare(dateTimeNow, _dtStartDate) > 0 && DateTime.Compare(dateTimeNow, _dtEndDate) < 0)
        {
            ddlDiscountPercentage.Text = _maxPercentage.ToString();
        }

        if (_providerComId == 41 || _providerComId == 43)
        {
            ddlDiscountPercentage.Text = "0";
        }

        if (lblRenewalStaus.Text == "1" || lblRenewalStaus.Text == "2")
        {
            ddlDiscountPercentage.Text = "0";
        }

        ddlDiscountPercentage_SelectedIndexChanged(null, null);
    }

    private void LoadMonthlyInstallment()
    {
        ddlCreditCard.Items.Clear();
        ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));

        ddlPaymentOption.Items.Clear();
        ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.Installment, "IP"));
        ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.AnnualPayment, "FP"));

        if (ddlBrokerProvider.SelectedIndex > 0)
        {
            string IPDiscount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IPDiscount");
            lblInterest.Text = Resources.CarInsurance.InterestFree;
            if (ddlBrokerProvider.Text == "11")
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));

                ddlCreditCard.Items.Clear();
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankCITI, "CITI"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));

                ddlGGDiscount.Items.Clear();
                ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));
            }
            else if (ddlBrokerProvider.Text == "29")
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));

                ddlCreditCard.Items.Clear();
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankBKK, "BKK"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankKTC, "KTC"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));

                ddlGGDiscount.Items.Clear();
                if (IPDiscount != string.Empty)
                {
                    ddlGGDiscount.Items.Add(new ListItem(IPDiscount.ToString() + " %", IPDiscount.ToString()));
                }
                ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));
            }
            else if (ddlBrokerProvider.Text == "32")
            {
                if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));

                    ddlGGDiscount.Items.Clear();
                    ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));

                    ddlGGDiscount.Items.Clear();
                    ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));


                    ddlPaymentOption.Items.Clear();
                    ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
                    ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.AnnualPayment, "FP"));
                }

                ddlCreditCard.Items.Clear();
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankBKK, "BKK"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankCITI, "CITI"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankKTC, "KTC"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankAYA, "AYA"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.CentralCard, "CTRL"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.RobinsonCard, "RBSN"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.HomeproCard, "HPRO"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));
            }
            else
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));

                ddlCreditCard.Items.Clear();
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));
            }
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.CashInstallment, "CHINS"));
            ddlCreditCard_SelectedIndexChanged(null, null);
            ddlNoofInstallments_SelectedIndexChanged(null, null);
        }
    }

    private void LoadBrokerDefault() 
    {
        try
        {
            if (ddlBrokerProvider.Text.Length > 0 && ddlGarageType.Text.Length > 0 && ddlBrokerCoverType.Text.Length > 0)
            {
                MyDatabase _myDB = new MyDatabase();

                string _strSelect = "Select TPBIA, TPBIP, TPPD, PAPassenger, MedicalExpense, BailBond, DEC, FireTheft, FloodCover " +
                    "from tblCXBrokerDefaultBenefits ";
                _strSelect = _strSelect + " WHERE CXBrokerProviderId = " + ddlBrokerProvider.Text;
                _strSelect = _strSelect + " AND GarageType = " + ddlGarageType.Text;
                _strSelect = _strSelect + " AND InsuranceType = " + ddlBrokerCoverType.SelectedValue;

                DataTable _dtDefaultValues = new DataTable("tblDefault");
                _dtDefaultValues = _myDB.GetDataTable(_strSelect);

                if (_dtDefaultValues != null && _dtDefaultValues.Rows.Count > 0)
                {
                    if (_dtDefaultValues.Rows[0]["TPBIA"] != DBNull.Value)
                    {
                        txtTPBIA.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["TPBIA"].ToString()).ToString("#,000");
                    }

                    if (_dtDefaultValues.Rows[0]["TPBIP"] != DBNull.Value)
                    {
                        txtTPBIP.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["TPBIP"].ToString()).ToString("#,000");
                    }

                    if (_dtDefaultValues.Rows[0]["TPPD"] != DBNull.Value)
                    {
                        txtTPPD.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["TPPD"].ToString()).ToString("#,000");
                    }

                    if (_dtDefaultValues.Rows[0]["PAPassenger"] != DBNull.Value)
                    {
                        txtPA.Text = _dtDefaultValues.Rows[0]["PAPassenger"].ToString();
                    }

                    if (_dtDefaultValues.Rows[0]["MedicalExpense"] != DBNull.Value)
                    {
                        txtMED.Text = _dtDefaultValues.Rows[0]["MedicalExpense"].ToString();
                    }

                    if (_dtDefaultValues.Rows[0]["BailBond"] != DBNull.Value)
                    {
                        txtBailBond.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["BailBond"].ToString()).ToString("#,000");
                    }


                    if (_dtDefaultValues.Rows[0]["DEC"] != DBNull.Value)
                    {
                        txtDeductible.Text = _dtDefaultValues.Rows[0]["DEC"].ToString();
                    }
                    if (_dtDefaultValues.Rows[0]["FireTheft"] != DBNull.Value)
                    {
                        txtFireTheft.Text = _dtDefaultValues.Rows[0]["FireTheft"].ToString();
                    }
                    if (_dtDefaultValues.Rows[0]["FloodCover"] != DBNull.Value)
                    {
                        txtFloodCoverAmount.Text = _dtDefaultValues.Rows[0]["FloodCover"].ToString();
                    }
                }
            }
        }
        catch (Exception Ex)
        {
            lblPremiumMessage.Text = Ex.Message;
        }
    }

    public void SixMonthIstallMents()
    {
        //For K Bank 6 Months Installments -- Start
        decimal _AnnualPremium = 0;
        decimal _AnnualPremiumWOD = 0;
        if (!decimal.TryParse(txtAnnualPremium.Text, out _AnnualPremium))
        {
            _AnnualPremium = 0;
        }
        if (!decimal.TryParse(txtFinalAnnualPremiumNoDisc.Text, out _AnnualPremiumWOD))
        {
            _AnnualPremiumWOD = 0;
        }
        if (_AnnualPremiumWOD < 5000 && ddlCreditCard.Text == "CHINS")
        {
            ddlNoofInstallments.Items.Clear();
            ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));

        }
        else if (_AnnualPremiumWOD >= 5000 && ddlCreditCard.Text == "CHINS")
        {
            Int32 NoofInstall = CheckCommencementDateforCashInstallment();
            if (ddlNoofInstallments.Text == "4")
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
            }
            else if (ddlNoofInstallments.Text == "3")
            {
                if (NoofInstall > 3)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
            }
            else if (ddlNoofInstallments.Text == "2")
            {
                if (NoofInstall > 3)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
                else if (NoofInstall > 2 && NoofInstall <= 3)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
            }
            else
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
            }
        }
        else if (_AnnualPremiumWOD >= 20000 && ddlCreditCard.Text == "KBANK")
        {
            if (ddlBrokerProvider.Text == "32")
            {
                if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                {
                    if (ddlNoofInstallments.Text == "3")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    }
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                }
            }
            else
            {
                if (ddlNoofInstallments.Text == "3")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
            }
        }
        else
        {
            if (ddlBrokerProvider.Text == "11")
            {
                if (ddlCreditCard.Text == "CITI")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
            }
            else if (ddlBrokerProvider.Text == "29")
            {
                if (ddlCreditCard.Text == "KBANK")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
                else if (ddlNoofInstallments.Text == "6")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                }
            }
            else if (ddlBrokerProvider.Text == "32")
            {
                if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                {
                    if (ddlCreditCard.Text == "KBANK")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    }
                }
                else 
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                }
            }
            else
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
            }
        }

        //For K Bank 6 Months Installments  -- End
    }
    
    private void LoadgentbyAdmin()
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            DataTable _dt = new DataTable("tblList");
            string _spName = "sprocCXCRMGetAgentList";

            SortedList paraList = new SortedList();
            paraList.Add("@AgentID", Session[General.UserId].ToString());
            _dt = _db.GetDataTableBySP(_spName, paraList);

            ddlAgentbyAdmin.Items.Clear();
            ddlAgentbyAdmin.Items.Add(new ListItem("None", "0"));
            if (_dt != null && _dt.Rows.Count > 0)
            {
                for (int i = 0; i < _dt.Rows.Count; i++)
                {
                    ddlAgentbyAdmin.Items.Add(new ListItem(_dt.Rows[i]["FULLNAME"].ToString(), _dt.Rows[i]["CEID"].ToString()));
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    private void InstallmentsCalculation()
    {
        SixMonthIstallMents();
        lblTitleLastInstallWDDesc.Text = "";
        lblTitleLastInstallWODDesc.Text = "";
        decimal _annualPremium = 0;
        decimal _annualPremiumNoDisc = 0;
        decimal _InstallmentInterest = 0;
        decimal _InstallmentannualPremiumWD = 0;
        decimal _InstallmentAmountWD = 0;
        decimal _InstallmentLastMonthAmountWD = 0;
        decimal _InstallmentannualPremiumWOD = 0;
        decimal _InstallmentAmountWOD = 0;
        decimal _InstallmentLastMonthAmountWOD = 0;

        string _strannualPremium = txtFinalAnnualPremium.Text.Replace(",", "");
        string _strannualPremiumNoDisc = txtFinalAnnualPremiumNoDisc.Text.Replace(",", "");
        if (!decimal.TryParse(_strannualPremium, out _annualPremium))
        {
            _annualPremium = 0;
        }
        if (!decimal.TryParse(_strannualPremiumNoDisc, out _annualPremiumNoDisc))
        {
            _annualPremiumNoDisc = 0;
        }

        if (_annualPremiumNoDisc < 5000 && ddlCreditCard.Text == "CHINS")
        {
            _InstallmentannualPremiumWD = 0;
            _InstallmentAmountWD = 0;
            _InstallmentLastMonthAmountWD = 0;
            _InstallmentannualPremiumWOD = 0;
            _InstallmentAmountWOD = 0;
            _InstallmentLastMonthAmountWOD = 0;
        }
        else if (_annualPremiumNoDisc >= 5000 && ddlCreditCard.Text == "CHINS")
        {
            _InstallmentannualPremiumWD = _annualPremium;
            _InstallmentannualPremiumWOD = _annualPremiumNoDisc;
        }
        else if (_annualPremium >= 4000 && ddlBrokerProvider.Text == "29")
        {
            if (ddlNoofInstallments.Text == "4")
            {
                _InstallmentInterest = Convert.ToDecimal(1.032);
            }
            else if (ddlNoofInstallments.Text == "6")
            {
                _InstallmentInterest = Convert.ToDecimal(1.048);
            }
            if (ddlCreditCard.Text == "KBANK")
            {
                _InstallmentannualPremiumWD = _annualPremium;
                _InstallmentannualPremiumWOD = _annualPremiumNoDisc;
            }
            else
            {
                _InstallmentannualPremiumWD = (_annualPremium * _InstallmentInterest);
                _InstallmentannualPremiumWOD = (_annualPremiumNoDisc * _InstallmentInterest);
            }
        }
        else if (_annualPremiumNoDisc >= 4000 && ddlBrokerProvider.Text == "32")
        {
            if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
            {
                _InstallmentannualPremiumWD = _annualPremiumNoDisc;
                _InstallmentannualPremiumWOD = _annualPremiumNoDisc;
            }
            else
            {
                _InstallmentannualPremiumWD = 0;
                _InstallmentAmountWD = 0;
                _InstallmentLastMonthAmountWD = 0;
                _InstallmentannualPremiumWOD = 0;
                _InstallmentAmountWOD = 0;
                _InstallmentLastMonthAmountWOD = 0;
            }
        }
        else if (_annualPremiumNoDisc >= 4000)
        {
            _InstallmentannualPremiumWD = _annualPremiumNoDisc;
            _InstallmentannualPremiumWOD = _annualPremiumNoDisc;
        }
        else
        {
            _InstallmentannualPremiumWD = 0;
            _InstallmentAmountWD = 0;
            _InstallmentLastMonthAmountWD = 0;
            _InstallmentannualPremiumWOD = 0;
            _InstallmentAmountWOD = 0;
            _InstallmentLastMonthAmountWOD = 0;
        }

        Int32 _Installments = Convert.ToInt32(ddlNoofInstallments.Text);
        Int32 _Install = _Installments - 1;
        decimal _TotalInstallMentWD = 0;
        decimal _TotalInstallMentWOD = 0;

        if (ddlBrokerProvider.Text == "29" && ddlCreditCard.Text != "CHINS")
        {
            if (_InstallmentannualPremiumWD > 0 && _Installments > 0)
            {
                _InstallmentAmountWD = Math.Ceiling(Convert.ToDecimal(_InstallmentannualPremiumWD / _Installments));
                _TotalInstallMentWD = Convert.ToDecimal(_InstallmentAmountWD * _Install);
                _InstallmentLastMonthAmountWD = Convert.ToDecimal(_InstallmentannualPremiumWD - _TotalInstallMentWD);
            }
        }
        else
        {
            _InstallmentAmountWD = 0;
            _TotalInstallMentWD = 0;
            _InstallmentLastMonthAmountWD = 0;
        }
        if (_InstallmentannualPremiumWOD > 0 && _Installments > 0)
        {
            if (ddlCreditCard.Text == "CHINS")
            {
                decimal tempInstall = 0;
                if (_Installments == 2)
                {
                    tempInstall = Convert.ToDecimal(_InstallmentannualPremiumWOD / 10);
                    _TotalInstallMentWOD = Math.Ceiling(Convert.ToDecimal(tempInstall * 5));
                    _InstallmentAmountWOD = (_InstallmentannualPremiumWOD - _TotalInstallMentWOD);
                    _InstallmentLastMonthAmountWOD = _TotalInstallMentWOD;
                }
                else if (_Installments == 3)
                {
                    tempInstall = Convert.ToDecimal(_InstallmentannualPremiumWOD / 10);
                    _TotalInstallMentWOD = Math.Ceiling(Convert.ToDecimal(tempInstall * 3));
                    _InstallmentAmountWOD = (_InstallmentannualPremiumWOD - (_TotalInstallMentWOD * 2));
                    _InstallmentLastMonthAmountWOD = _TotalInstallMentWOD;
                }
                else if (_Installments == 4)
                {
                    tempInstall = Convert.ToDecimal(_InstallmentannualPremiumWOD / 4);
                    _TotalInstallMentWOD = Math.Ceiling(tempInstall);
                    _InstallmentAmountWOD = (_InstallmentannualPremiumWOD - (_TotalInstallMentWOD * 3));
                    _InstallmentLastMonthAmountWOD = _TotalInstallMentWOD;
                }
            }
            else
            {
                _InstallmentAmountWOD = Math.Ceiling(Convert.ToDecimal(_InstallmentannualPremiumWOD / _Installments));
                _TotalInstallMentWOD = Convert.ToDecimal(_InstallmentAmountWOD * _Install);
                _InstallmentLastMonthAmountWOD = Convert.ToDecimal(_InstallmentannualPremiumWOD - _TotalInstallMentWOD);
            }
        }

        if (ddlBrokerProvider.Text == "29" && ddlCreditCard.Text != "CHINS")
        {
            lblTotalGrossPremiumWD.Text = _InstallmentannualPremiumWD.ToString("#0.00");
        }
        else
        {
            lblTotalGrossPremiumWD.Text = Resources.CarInsurance.NoDiscount;
        }
        lblFirstInstallmentWD.Text = _InstallmentAmountWD.ToString("#0.00");
        lblLastInstallmentWD.Text = _InstallmentLastMonthAmountWD.ToString("#0.00");
        lblTotalGrossPremiumWOD.Text = _InstallmentannualPremiumWOD.ToString("#0.00");
        lblFirstInstallmentWOD.Text = _InstallmentAmountWOD.ToString("#0.00");
        lblLastInstallmentWOD.Text = _InstallmentLastMonthAmountWOD.ToString("#0.00");
        if (ddlCreditCard.Text == "CHINS")
        {
            lblTitleFirstInstallWD.Text = Resources.CarInsurance.Installment;
            lblTitleFirstInstallWOD.Text = Resources.CarInsurance.Installment;
            lblTitleLastInstallWD.Text = Resources.CarInsurance.Installment;
            lblTitleLastInstallWOD.Text = Resources.CarInsurance.Installment;
            if (_Installments == 2)
            {
                lblTitleLastInstallWDDesc.Text = "(Last " + Resources.CarInsurance.Month + ")";
                lblTitleLastInstallWODDesc.Text = "(Last " + Resources.CarInsurance.Month + ")";
            }
            else if (_Installments == 3)
            {
                lblTitleLastInstallWDDesc.Text = "(Last 2 " + Resources.CarInsurance.Month + ")";
                lblTitleLastInstallWODDesc.Text = "(Last 2 " + Resources.CarInsurance.Month + ")";
            }
            else if (_Installments == 3)
            {
                lblTitleLastInstallWDDesc.Text = "(Last 3 " + Resources.CarInsurance.Months + ")";
                lblTitleLastInstallWODDesc.Text = "(Last 3 " + Resources.CarInsurance.Months + ")";
            }

            lblFirstInstallmentWDdesc.Text = "(1st " + Resources.CarInsurance.Month + ")";
            lblFirstInstallmentWODdesc.Text = "(1st " + Resources.CarInsurance.Month + ")";
        }
        else
        {
            lblTitleFirstInstallWD.Text = Resources.CarInsurance.Installment;
            lblTitleFirstInstallWOD.Text = Resources.CarInsurance.Installment;
            lblTitleLastInstallWD.Text = Resources.CarInsurance.LastMonthInstallment;
            lblTitleLastInstallWOD.Text = Resources.CarInsurance.LastMonthInstallment;

            lblFirstInstallmentWDdesc.Text = "(1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months + ")";
            lblFirstInstallmentWODdesc.Text = "(1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months + ")";
        }
    }

    private void ShowLastQuotationSendDate(Int64 CompanyId)
    {
        FleetBrokerPremiumDB _db = new FleetBrokerPremiumDB();
        string _lastSendStatus = _db.GetLastQuotationSendDate(CompanyId, 1);
        if (_lastSendStatus != string.Empty)
        {
            string[] strLastSendValues = _lastSendStatus.Split(',');
            lblSendQuotationMessage.Text = Resources.General.QuotationSent + " > " + strLastSendValues[0];
            txtConfirmEmail.Text = strLastSendValues[0];

            lblSendQuotationMessage.Text += " > " + Convert.ToDateTime(strLastSendValues[1]).ToString("dd/MMM/yyyy hh:mm tt");
        }
    }

    #endregion

    #region Return Methods

    public bool CheckCXBrokerPremiumCount(Int64 CarID, Int64 CustomerID)
    {
        bool _Result = false;
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "[sprocCXBrokerPremiumGetCount]";
        _sPara.Add("@CarID", CarID);
        _sPara.Add("@CustomerID", CustomerID);
        _sPara.Add("@ProductType", "CIN");

        object _objCount = _db.ExecuteScalarSP(_spName, _sPara);
        if (_objCount != null && Convert.ToInt32(_objCount) > 0)
        {
            _Result = true;
        }

        return _Result;
    }

    private string GetBankName(string BankCode)
    {
        string _BankName = "";
        if (BankCode == "CHINS")
        {
            _BankName = Resources.CarInsurance.CashInstallment;
        }
        else if (BankCode == "BKK")
        {
            _BankName = Resources.CarInsurance.BankBKK;
        }
        else if (BankCode == "KBANK")
        {
            _BankName = Resources.CarInsurance.BankK;
        }
        else if (BankCode == "KTC")
        {
            _BankName = Resources.CarInsurance.BankKTC;
        }
        else if (BankCode == "CITI")
        {
            _BankName = Resources.CarInsurance.BankCITI;
        }
        else if (BankCode == "AYA")
        {
            _BankName = Resources.CarInsurance.BankAYA;
        }
        else if (BankCode == "CTRL")
        {
            _BankName = Resources.CarInsurance.CentralCard;
        }
        else if (BankCode == "RBSN")
        {
            _BankName = Resources.CarInsurance.RobinsonCard;
        }
        else if (BankCode == "HPRO")
        {
            _BankName = Resources.CarInsurance.HomeproCard;
        }
        return _BankName;
    }

    public DataSet GetBrokerPremiumbyPremiumId(Int64 FleetBrokerPremiumId)
    {
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocFleetBrokerPremiumDiscountPercentageSelectSingleItem";
        _sPara.Add("@FleetBrokerPremiumId", FleetBrokerPremiumId);
        DataSet _ds = new DataSet();
        return _ds = _db.GetDataSet(_spName, _sPara);
    }

    public Int16 GetCustomerType(string RefCEUserId)
    {
        Int16 IsThai = 1;
        MyDatabase _db = new MyDatabase();
        string strSql = "SELECT IsThai = CASE WHEN Ninfo7 IS NULL THEN 1 ELSE Ninfo7 END FROM tblCEUsrProfile WHERE RefCEUserId = " + RefCEUserId;
        object _result = _db.ExecuteScalarSqlStatement(strSql);
        if (_result != null)
        {
            if (!Int16.TryParse(_result.ToString(), out IsThai))
            {
                IsThai = 1;
            }
        }
        return IsThai;
    }

    private bool GGSpecialPremiumValidation()
    {
        bool _IsValid = false;
        try
        {
            if (txtGG.Text.Trim() == "GGSPECIAL")
            {
                MyDatabase _db = new MyDatabase();
                DataTable _dtSelect = new DataTable();
                string _strSelect = "SELECT CASE WHEN LEN(CD.Info16) > 0 THEN CD.Info16 ELSE CP.NCDPercent END AS NCDPercent "
                               + " FROM tblCarPolicy CP INNER JOIN tblCarDetailTH CD ON CD.CarId = CP.CECarId "
                               + " WHERE CP.RefCEUserId = " + txtCustomerId.Text + " AND CP.CECarId= " + txtCarId.Text;
                _dtSelect = _db.GetDataTable(_strSelect);
                if (_dtSelect.Rows.Count > 0 && _dtSelect.Rows[0]["NCDPercent"] != DBNull.Value != null && _dtSelect.Rows[0]["NCDPercent"].ToString() != string.Empty)
                {
                    if (_dtSelect.Rows[0]["NCDPercent"].ToString().Trim() == "50")
                    {
                        _IsValid = true;
                    }
                }
            }
            else
            {
                _IsValid = true;
            }
        }
        catch (Exception ex)
        {
            _IsValid = false;
        }
        return _IsValid;
    }

    private Int32 CheckCommencementDateforCashInstallment()
    {
        try
        {
            TimeSpan ts;
            Int32 days = 0;
            Int32 Installment = 0;
            DateTime _dtCoverCommDate = dateTimeNow;
            if (DateTime.TryParse(lblEditCoverCommencementDate.Text, out _dtCoverCommDate))
            {
                DateTime _dtNow = new DateTime(dateTimeNow.Year, dateTimeNow.Month, dateTimeNow.Day);

                ts = (_dtCoverCommDate.Date - _dtNow.Date);
                days = ts.Days;

                //Start 19 Jan 2015
                if (int.Parse(dateTimeNow.ToString("yyyyMMdd")) >= 20150119)
                {
                    if (days < 30 && days < 60)
                    {
                        Installment = 2;
                    }
                    else if (days >= 60 && days <= 90)
                    {
                        Installment = 3;
                    }
                    else if (days > 90)
                    {
                        Installment = 4;
                    }
                    else
                    {
                        Installment = 0;
                    }
                }
                else
                {
                    if (days > 30 && days <= 60)
                    {
                        Installment = 2;
                    }
                    else if (days > 60 && days <= 90)
                    {
                        Installment = 3;
                    }
                    else if (days > 90)
                    {
                        Installment = 4;
                    }
                    else
                    {
                        Installment = 0;
                    }
                }
            }
            else
            {
                Installment = 0;
            }
            return Installment;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

    #endregion

    #region Excel

    public string GenerateQuoteFile(string PROCESS, string FleetCarIds)
    {
        Int16 LangOption = Convert.ToInt16(lblLangOption.Text);
        Int64 CompanyId = Convert.ToInt64(txtCompanyId.Text);
        Int32 _QuoteCount = 0;
        Label lblContent = new Label();
        string AgentEmail = Session[General.SMTPReplyTo].ToString();
        string AgentName = Session[General.UserName].ToString();
        string AgentContactNo = Session[General.UserPhoneNo].ToString();
        string AgentLicenseNo = "";
        string AgentSupervisor = "";
        string AgentSupLicenseNo = "";
        string _html = "";
        string _filePath = "";
        string _fileName = "FLEET_" + CompanyId.ToString("0000");
        _QuoteCount = grvQuoteList.Rows.Count;

        Int16 IsThai = 1;
        if (chkIsEN.Checked)
        {
            IsThai = 0;
        }
        decimal TotalFullPayment = 0;
        decimal TotalInstallPayment = 0;
        DataSet _dsQuoteDetails = new DataSet();
        DataTable _dtCompany = new DataTable();
        DataTable _dtQuoteList = new DataTable();
        MyDatabase _db = new MyDatabase();
        string _spName = "sprocFleetBrokerPremiumSelectItemListByCompanyId";

        SortedList _spara = new SortedList();
        _spara.Add("@CompanyId", CompanyId);
        _spara.Add("@ProductType", "CIN");
        _spara.Add("@LangOption", LangOption);
        if (FleetCarIds.ToString() != "")
        {
            _spara.Add("@FleetCarIds", FleetCarIds);
        }

        _dsQuoteDetails = _db.GetDataSet(_spName, _spara);
        if (_dsQuoteDetails != null && _dsQuoteDetails.Tables.Count > 0)
        {
            _dtQuoteList = _dsQuoteDetails.Tables[0];
            _QuoteCount = _dtQuoteList.Rows.Count;
        }
        if (_dsQuoteDetails != null && _dsQuoteDetails.Tables.Count > 1)
        {
            _dtCompany = _dsQuoteDetails.Tables[1];
        }

        _spara.Clear();
        _spara.Add("@AgentId", Session[General.UserId].ToString());
        DataTable _dtAgentList = new DataTable("tblAgentList");
        _dtAgentList = _db.GetDataTableBySP("sprocCXCRMAgentLicense", _spara);
        if (_dtAgentList != null)
        {
            foreach (DataRow drAgentList in _dtAgentList.Rows)
            {
                if (drAgentList["CEID"].ToString() == Session[General.UserId].ToString())
                {
                    if (drAgentList["LicenseNo"] != DBNull.Value)
                        AgentLicenseNo = drAgentList["LicenseNo"].ToString();
                }
                else
                {
                    if (IsThai == 1)
                    {
                        AgentSupervisor = drAgentList["AgentName"].ToString();
                    }
                    else
                    {
                        AgentSupervisor = drAgentList["AgentNameEN"].ToString();
                    }

                    if (drAgentList["LicenseNo"] != DBNull.Value)
                        AgentSupLicenseNo = drAgentList["LicenseNo"].ToString();
                }
            }
        }

        #region variables
        string[] _BrokerProvider = new string[_QuoteCount];
        string[] _CarMakeModel = new string[_QuoteCount];
        string[] _VehicleType = new string[_QuoteCount];
        string[] _NCB = new string[_QuoteCount];
        string[] _LicensedPlate = new string[_QuoteCount];
        string[] _Year = new string[_QuoteCount];
        string[] _NameDriver = new string[_QuoteCount];
        string[] _PolicyStartDate = new string[_QuoteCount];
        string[] _InsuranceCompany = new string[_QuoteCount];
        string[] _Insurer = new string[_QuoteCount];
        string[] _ReferenceNumber = new string[_QuoteCount];
        string[] _GarageType = new string[_QuoteCount];
        string[] _BodilyInjury = new string[_QuoteCount];
        string[] _LiabliltyBody = new string[_QuoteCount];
        string[] _LiabliltyProperty = new string[_QuoteCount];
        string[] _Deductible = new string[_QuoteCount];
        string[] _OwnDamage = new string[_QuoteCount];
        string[] _FireTheft = new string[_QuoteCount];
        string[] _FloodCover = new string[_QuoteCount];
        string[] _PersonalAccident = new string[_QuoteCount];
        string[] _BailBond = new string[_QuoteCount];
        string[] _Compulsory = new string[_QuoteCount];
        string[] _Voluntary = new string[_QuoteCount];
        string[] _Duty = new string[_QuoteCount];
        string[] _Vat = new string[_QuoteCount];
        string[] _GrossPremium = new string[_QuoteCount];
        string[] _NetPremium = new string[_QuoteCount];
        string[] _FullPayment = new string[_QuoteCount];
        string[] _InstallmentPayment = new string[_QuoteCount];
        string[] _MonthlyInstallment = new string[_QuoteCount];
        string[] _NoofInstallments = new string[_QuoteCount];
        string[] _CreditCard = new string[_QuoteCount];
        string[] _InterestFree = new string[_QuoteCount];
        string[] _Bank = new string[_QuoteCount];
        string[] _PaymentOption = new string[_QuoteCount];

        string ContactPerson = "";
        string ContactNo = "";
        string FleetRefNo = "FLEET" + Convert.ToInt32(txtCompanyId.Text).ToString("0000");
        if (_dtCompany != null && _dtCompany.Rows.Count > 0)
        {
            ContactPerson = _dtCompany.Rows[0]["ContactPerson"].ToString();
            ContactNo = _dtCompany.Rows[0]["ContactNo1"].ToString();
        }
        #endregion

        for (int i = 0; i < _QuoteCount; i++)
        {
            if (_dtQuoteList != null && _dtQuoteList.Rows.Count > 0)
            {
                #region Values assign to variables

                _BrokerProvider[i] = _dtQuoteList.Rows[i]["CXBrokerProviderId"].ToString();
                _CarMakeModel[i] = _dtQuoteList.Rows[i]["MakeModelDesc"].ToString();
                //_VehicleType[i] = _dtQuoteList.Rows[i]["PlanType"].ToString();
                _NCB[i] = _dtQuoteList.Rows[i]["NCDPercent"].ToString();
                _LicensedPlate[i] = _dtQuoteList.Rows[i]["CarPlate"].ToString();
                _Year[i] = _dtQuoteList.Rows[i]["ManufactYear"].ToString();
                _NameDriver[i] = _dtQuoteList.Rows[i]["NameDriverStatus"].ToString();

                DateTime _CoverageDate = dateTimeNow;
                if (!DateTime.TryParse(_dtQuoteList.Rows[i]["CoverageCommenceDate"].ToString(), out _CoverageDate))
                {
                    _CoverageDate = dateTimeNow;
                }
                string commdate = string.Format("{0:dd}", _CoverageDate.Day.ToString("00"));
                commdate = commdate + "/" + string.Format("{0:MM}", _CoverageDate.Month.ToString("00"));
                commdate = commdate + "/" + string.Format("{0:yyyy}", _CoverageDate.Year.ToString());

                _PolicyStartDate[i] = commdate.ToString();
                _InsuranceCompany[i] = _dtQuoteList.Rows[i]["CurrentInsurer"].ToString();
                _Insurer[i] = _dtQuoteList.Rows[i]["CompanyName"].ToString();
                _ReferenceNumber[i] = _dtQuoteList.Rows[i]["QuoteRefNo"].ToString();
                _GarageType[i] = _dtQuoteList.Rows[i]["WorkShopDesc"].ToString();
                _BodilyInjury[i] = _dtQuoteList.Rows[i]["TPBIP"].ToString();
                _LiabliltyBody[i] = _dtQuoteList.Rows[i]["TPBIA"].ToString();
                _LiabliltyProperty[i] = _dtQuoteList.Rows[i]["TPPD"].ToString();
                _Deductible[i] = _dtQuoteList.Rows[i]["DEC"].ToString();
                _OwnDamage[i] = _dtQuoteList.Rows[i]["OwnDamage"].ToString();
                _FireTheft[i] = _dtQuoteList.Rows[i]["FireTheft"].ToString();
                if (_dtQuoteList.Rows[i]["FloodCover"] != DBNull.Value)
                {
                    _FloodCover[i] = _dtQuoteList.Rows[i]["FloodCover"].ToString();
                }
                else
                {
                    _FloodCover[i] = " ";
                }
                _PersonalAccident[i] = _dtQuoteList.Rows[i]["PADriver"].ToString();
                _BailBond[i] = _dtQuoteList.Rows[i]["BailBond"].ToString();
                decimal TotalCMI = 0;
                if (!decimal.TryParse(_dtQuoteList.Rows[i]["TotalCMI"].ToString(), out TotalCMI))
                {
                    _Compulsory[i] = _dtQuoteList.Rows[i]["TotalCMI"].ToString();
                }
                else
                {
                    _Compulsory[i] = TotalCMI.ToString("#,000.00");
                }
                decimal TotalVMI = 0;
                if (!decimal.TryParse(_dtQuoteList.Rows[i]["TotalVMI"].ToString(), out TotalVMI))
                {
                    _Voluntary[i] = _dtQuoteList.Rows[i]["TotalVMI"].ToString();
                    _GrossPremium[i] = _dtQuoteList.Rows[i]["TotalVMI"].ToString();
                }
                else
                {
                    _Voluntary[i] = TotalVMI.ToString("#,000.00");
                    _GrossPremium[i] = TotalVMI.ToString("#,000.00");
                }
                _NetPremium[i] = _dtQuoteList.Rows[i]["NetPremium"].ToString();
                _Duty[i] = _dtQuoteList.Rows[i]["Duty"].ToString();
                _Vat[i] = Convert.ToSingle(_dtQuoteList.Rows[i]["VAT"].ToString()).ToString("#,000.00"); 
                _Bank[i] = _dtQuoteList.Rows[i]["Bank"].ToString();
                _PaymentOption[i] = _dtQuoteList.Rows[i]["PaymentOption"].ToString();
                if (_PaymentOption[i] == "FP")
                {
                    _FullPayment[i] = Convert.ToSingle(_dtQuoteList.Rows[i]["Premium"].ToString()).ToString("#,000.00");
                    _NoofInstallments[i] = "3";
                }
                else if (_PaymentOption[i] == "IP")
                {
                    _FullPayment[i] = (Convert.ToSingle(_Compulsory[i].ToString()) + Convert.ToSingle(_Voluntary[i].ToString())).ToString("#,000.00");
                    _NoofInstallments[i] = _dtQuoteList.Rows[i]["NoofInstallMent"].ToString();
                }

                _InterestFree[i] = "Yes";
                if (_BrokerProvider[i].ToString() == "29" && _Bank[i].ToString() != "CHINS")
                {
                    if (_Bank[i].ToString() == "KBANK")
                    {
                        _InterestFree[i] = "Yes";
                    }
                    else
                    {
                        _InterestFree[i] = "No";
                    }
                    _InstallmentPayment[i] = Convert.ToSingle(_dtQuoteList.Rows[i]["IPFinalAnnualPremiumWD"].ToString()).ToString("#,000.00");
                }
                else
                {
                    _InstallmentPayment[i] = Convert.ToSingle(_dtQuoteList.Rows[i]["IPFinalAnnualPremiumWOD"].ToString()).ToString("#,000.00");
                }

                if (_PaymentOption[i] == "IP")
                {
                    if (_Bank[i].ToString() == "CHINS")
                    {
                        if (_NoofInstallments[i] == "4")
                        {
                            _MonthlyInstallment[i] = _NoofInstallments[i].ToString() + " (25:25:25:25)";
                        }
                        else if (_NoofInstallments[i] == "3")
                        {
                            _MonthlyInstallment[i] = _NoofInstallments[i].ToString() + " (40:30:30)";
                        }
                        else
                        {
                            _MonthlyInstallment[i] = _NoofInstallments[i].ToString() + " (50:50)";
                        }


                    }
                    else
                    {
                        _MonthlyInstallment[i] = _NoofInstallments[i].ToString() + "*(" + (Convert.ToSingle(_InstallmentPayment[i].ToString()) / (Convert.ToInt32(_NoofInstallments[i].ToString()))).ToString("#,000.00") + ")";
                    }

                    //Yui@15072014
                    if (_Bank[i].ToString() == "KBANK")
                    {
                        _CreditCard[i] = Resources.CarInsurance.KBANKCreditCard; //GetBankName(_BankCode); 
                    }
                    else
                    {
                        _CreditCard[i] = GetBankName(_Bank[i].ToString());
                    }
                }
                else
                {
                    _NoofInstallments[i] = "3";
                    _InstallmentPayment[i] = Convert.ToSingle(_dtQuoteList.Rows[i]["IPFinalAnnualPremiumWOD"].ToString()).ToString("#,000.00");
                    _MonthlyInstallment[i] = _NoofInstallments[i].ToString() + "*(" + (Convert.ToSingle(_InstallmentPayment[i].ToString()) / (Convert.ToInt32(_NoofInstallments[i].ToString()))).ToString("#,000.00") + ")";
                    _CreditCard[i] = Resources.CarInsurance.KBANKCreditCard; //GetBankName("KBANK");
                    _InterestFree[i] = "Yes";
                }
                _VehicleType[i] = " ";
                #endregion

                TotalFullPayment = TotalFullPayment + Convert.ToDecimal(_FullPayment[i].Replace(",", ""));
                TotalInstallPayment = TotalInstallPayment + Convert.ToDecimal(_InstallmentPayment[i].Replace(",", ""));
            }
        }
        string Empty = ".";
        Int32 TotalCalsPan = _QuoteCount + 1;
        Int32 CalsPan = _QuoteCount;

        #region Excel
        _html += "<html>";
        _html += "<head>";
        _html += "<meta http-equiv='content-type' content='text/html; charset=UTF-8'>";
        _html += "</head>";
        _html += "<body>";

        #region Company Details
        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr>";
        _html += "<td colspan='" + CalsPan.ToString() + "'>&nbsp;</td>";
        _html += "<td><img src='http://www.gluaygluay.com/management/images/logos/gluaygluay_small.png' alt='gluaygluay' width='50px' height='40px' /></td>";
        _html += "</tr>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:22;'>Comparexpress Insurance broker ( Thailand ) Ltd</td></tr>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:22;'>Non-Life Insurance Broker Licensed Number ว00016/2553</td></tr>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:22;'>2 K.C.C Bdg, 2nd Floor Silom Soi9, Silom Road Bangrak Bangkok 10500</td></tr>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:22;'>Tel: 02-268-8222 fax 02-266-6339</td></tr>";
        _html += "</table>";

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "'>&nbsp;</td></tr>";
        _html += "</table>";

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:22; font-weight:bold;'>Fleet Car Insurance Quotes</td></tr>";
        _html += "<tr><td style='width:200px;' style=' height:22;'>Name</td><td colspan='" + CalsPan.ToString() + "'>: " + ContactPerson.ToString() + "</td></tr>";
        _html += "<tr><td style='width:200px;' style=' height:22;'>Contact No</td><td colspan='" + CalsPan.ToString() + "'>: " + ContactNo.ToString() + "</td></tr>";
        _html += "<tr><td style='width:200px;' style=' height:22;'>Fleet Reference Number </td><td colspan='" + CalsPan.ToString() + "'>: " + FleetRefNo.ToString() + "</td></tr>";
        _html += "</table>";
        #endregion

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "'>&nbsp;</td></tr>";
        _html += "</table>";

        #region Body
        _html += "<table width='100%' cellpadding='1' cellspacing='1' border='1'>";
        _html += "<tr>";
        _html += "<td align='left' style='background-color:#FFFF00; font-weight:bold; height:19;'>Number of Car</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#FFFF00; font-weight:bold;'>" + j.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Car Make / Model </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _CarMakeModel[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Vehicle type or usage</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _VehicleType[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Good record Discount (NCB) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _NCB[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Licensed Plate </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _LicensedPlate[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Year</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _Year[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Policy start Date</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _PolicyStartDate[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Insurance Company </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _InsuranceCompany[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#FFFF00; font-weight:bold; height:19;'>Policy Details</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#FFFF00; color:#FFFF00;'>" + Empty.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Insurance Company </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _Insurer[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Reference Number </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _ReferenceNumber[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Garage Type </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _GarageType[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#FFFF00; font-weight:bold; height:19;'>Third Party Cover</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#FFFF00; color:#FFFF00;'>" + Empty.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Bodily Injury/Death ( per person ) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _BodilyInjury[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Liablilty for Bodily Injury / Death </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _LiabliltyBody[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Liablilty for Property Damage  </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _LiabliltyProperty[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Deductible (per accident ) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _Deductible[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#FFFF00; font-weight:bold; height:19;'>Owner Damage Cover</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#FFFF00; color:#FFFF00;'>" + Empty.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Own Damage</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _OwnDamage[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Fire / Theft </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _FireTheft[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD;'>Flood Cover</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD; height:19;'>" + _FloodCover[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#FFFF00; font-weight:bold; height:19;'>Add. Cover. Per Endorsement </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#FFFF00; color:#FFFF00;'>" + Empty.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Personal Accident ( per person)</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _PersonalAccident[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Bail Bond ( per accident) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _BailBond[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>CMI ( Compulsory Insurance ) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _Compulsory[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD;'>" + Empty.ToString() + "</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD; color:#BDBDBD;'>" + Empty.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Voluntary (VMI ) Net premium</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _NetPremium[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Duty stamp 0.4%</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _Duty[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Vat7% </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _Vat[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>VMI Gross Premium </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _GrossPremium[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#FFFF00; font-weight:bold; height:19;'>Payment Options : </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#FFFF00; color:#FFFF00;'>" + Empty.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>1) Full Payment (after special discount) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _FullPayment[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>2) Monthly Installment  </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _InstallmentPayment[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Number of Installments</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _MonthlyInstallment[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Credit Card by </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _CreditCard[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>0% Interest Free </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _InterestFree[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";
        _html += "</table>";
        #endregion

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "'>&nbsp;</td></tr>";
        _html += "</table>";

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Total Full Payment</td><td colspan='" + CalsPan.ToString() + "'>: " + TotalFullPayment.ToString("#,000.00") + "</td></tr>";
        _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Total Installment Payment</td><td colspan='" + CalsPan.ToString() + "'>: " + TotalInstallPayment.ToString("#,000.00") + "</td></tr>";
        _html += "</table>";

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "'>&nbsp;</td></tr>";
        _html += "</table>";

        #region Remarks
        string _remarks = Resources.Proposal.RemarksMsg1;
        _remarks = _remarks.Replace("<br/>", "^");
        string[] Remarks = _remarks.Split('^');
        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:19; font-weight:bold;'>" + Resources.Proposal.Remarks + "</td></tr>";
        for (int a = 0; a < Remarks.Length; a++)
        {
            _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:19;'>" + Remarks[a].ToString() + "</td></tr>";
        }
        _html += "</table>";
        #endregion

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "'>&nbsp;</td></tr>";
        _html += "</table>";

        #region Agent Details
        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Broker</td><td colspan='" + CalsPan.ToString() + "'>: " + AgentName.ToString() + "</td></tr>";
        _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Email</td><td colspan='" + CalsPan.ToString() + "'>: " + AgentEmail.ToString() + "</td></tr>";
        _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Contact No</td><td colspan='" + CalsPan.ToString() + "'>: " + AgentContactNo.ToString() + "</td></tr>";
        if (AgentLicenseNo.ToString().Trim() != "")
        {
            _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>License No</td><td colspan='" + CalsPan.ToString() + "'>: " + AgentLicenseNo.ToString() + "</td></tr>";

        }
        else
        {
            _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Supervisor Name</td><td colspan='" + CalsPan.ToString() + "'>: " + AgentSupervisor.ToString() + "</td></tr>";
            _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Supervisor License No</td><td colspan='" + CalsPan.ToString() + "'>: " + AgentSupLicenseNo.ToString() + "</td></tr>";
        }
        _html += "</table>";
        #endregion

        _html += "</body>";
        _html += "</html>";
        #endregion

        if (PROCESS == "SEND")
        {
            lblContent.Text = _html;
            MyIO myio = new MyIO();
            string[] filecontent = new string[1];
            filecontent[0] = lblContent.Text.ToString();
            _filePath = GetExcelFilePath(Convert.ToInt64(txtCompanyId.Text.Trim()));
            myio.WriteNewFile(_filePath, _fileName + ".xls", filecontent);
        }
        else if (PROCESS == "DOWNLOAD")
        {
            lblContent.Text = _html;
            ExportGridView(_fileName, lblContent);
        }
        return (_filePath + _fileName + ".xls");


    }

    public void DownloadQuoteFile()
    {
        Int16 LangOption = Convert.ToInt16(lblLangOption.Text);
        Int64 CompanyId = Convert.ToInt64(txtCompanyId.Text);
        Int32 _QuoteCount = 0;
        Label lblContent = new Label();
        string AgentEmail = Session[General.SMTPReplyTo].ToString();
        string AgentName = Session[General.UserName].ToString();
        string AgentContactNo = Session[General.UserPhoneNo].ToString();
        string AgentLicenseNo = "";
        string AgentSupervisor = "";
        string AgentSupLicenseNo = "";
        string _html = "";
        string _fileName = "FLEET_" + CompanyId.ToString("0000");
        _QuoteCount = grvQuoteList.Rows.Count;

        Int16 IsThai = 1;
        if (LangOption == 2)
        {
            IsThai = 0;
        }
        decimal TotalFullPayment = 0;
        decimal TotalInstallPayment = 0;
        DataSet _dsQuoteDetails = new DataSet();
        DataTable _dtCompany = new DataTable();
        DataTable _dtQuoteList = new DataTable();
        MyDatabase _db = new MyDatabase();
        string _spName = "sprocFleetBrokerPremiumSelectItemListByCompanyId";

        SortedList _spara = new SortedList();
        _spara.Add("@CompanyId", CompanyId);
        _spara.Add("@ProductType", "CIN");
        _spara.Add("@LangOption", LangOption);

        _dsQuoteDetails = _db.GetDataSet(_spName, _spara);
        if (_dsQuoteDetails != null && _dsQuoteDetails.Tables.Count > 0)
        {
            _dtQuoteList = _dsQuoteDetails.Tables[0];
            _QuoteCount = _dtQuoteList.Rows.Count;
        }
        if (_dsQuoteDetails != null && _dsQuoteDetails.Tables.Count > 1)
        {
            _dtCompany = _dsQuoteDetails.Tables[1];
        }

        _spara.Clear();
        _spara.Add("@AgentId", Session[General.UserId].ToString());
        DataTable _dtAgentList = new DataTable("tblAgentList");
        _dtAgentList = _db.GetDataTableBySP("sprocCXCRMAgentLicense", _spara);
        if (_dtAgentList != null)
        {
            foreach (DataRow drAgentList in _dtAgentList.Rows)
            {
                if (drAgentList["CEID"].ToString() == Session[General.UserId].ToString())
                {
                    if (drAgentList["LicenseNo"] != DBNull.Value)
                        AgentLicenseNo = drAgentList["LicenseNo"].ToString();
                }
                else
                {
                    if (IsThai == 1)
                    {
                        AgentSupervisor = drAgentList["AgentName"].ToString();
                    }
                    else
                    {
                        AgentSupervisor = drAgentList["AgentNameEN"].ToString();
                    }

                    if (drAgentList["LicenseNo"] != DBNull.Value)
                        AgentSupLicenseNo = drAgentList["LicenseNo"].ToString();
                }
            }
        }

        #region variables
        string[] _BrokerProvider = new string[_QuoteCount];
        string[] _CarMakeModel = new string[_QuoteCount];
        string[] _VehicleType = new string[_QuoteCount];
        string[] _NCB = new string[_QuoteCount];
        string[] _LicensedPlate = new string[_QuoteCount];
        string[] _Year = new string[_QuoteCount];
        string[] _NameDriver = new string[_QuoteCount];
        string[] _PolicyStartDate = new string[_QuoteCount];
        string[] _InsuranceCompany = new string[_QuoteCount];
        string[] _Insurer = new string[_QuoteCount];
        string[] _ReferenceNumber = new string[_QuoteCount];
        string[] _GarageType  = new string[_QuoteCount];
        string[] _BodilyInjury = new string[_QuoteCount];
        string[] _LiabliltyBody = new string[_QuoteCount];
        string[] _LiabliltyProperty = new string[_QuoteCount];
        string[] _Deductible = new string[_QuoteCount];
        string[] _OwnDamage = new string[_QuoteCount];
        string[] _FireTheft  = new string[_QuoteCount];
        string[] _FloodCover  = new string[_QuoteCount];
        string[] _PersonalAccident = new string[_QuoteCount];
        string[] _BailBond = new string[_QuoteCount];
        string[] _Compulsory = new string[_QuoteCount];
        string[] _Voluntary = new string[_QuoteCount];
        string[] _Duty = new string[_QuoteCount];
        string[] _Vat = new string[_QuoteCount];
        string[] _GrossPremium = new string[_QuoteCount];
        string[] _FullPayment = new string[_QuoteCount];
        string[] _InstallmentPayment = new string[_QuoteCount];
        string[] _MonthlyInstallment = new string[_QuoteCount];
        string[] _NoofInstallments  = new string[_QuoteCount];
        string[] _CreditCard = new string[_QuoteCount];
        string[] _InterestFree = new string[_QuoteCount];
        string[] _Bank = new string[_QuoteCount];
        string[] _PaymentOption = new string[_QuoteCount];

        string ContactPerson = "";
        string ContactNo = "";
        string FleetRefNo = "FLEET" + Convert.ToInt32(txtCompanyId.Text).ToString("0000");
        if (_dtCompany != null && _dtCompany.Rows.Count > 0)
        {
            ContactPerson = _dtCompany.Rows[0]["ContactPerson"].ToString();
            ContactNo = _dtCompany.Rows[0]["ContactNo1"].ToString();
        }
        #endregion

        for (int i = 0; i < _QuoteCount; i++)
        {            
            if (_dtQuoteList != null && _dtQuoteList.Rows.Count > 0)
            {
                #region Values assign to variables

                _BrokerProvider[i] = _dtQuoteList.Rows[i]["CXBrokerProviderId"].ToString();
                _CarMakeModel[i] = _dtQuoteList.Rows[i]["MakeModelDesc"].ToString();
                //_VehicleType[i] = _dtQuoteList.Rows[i]["PlanType"].ToString();
                _NCB[i] = _dtQuoteList.Rows[i]["NCDPercent"].ToString();
                _LicensedPlate[i] = _dtQuoteList.Rows[i]["CarPlate"].ToString();
                _Year[i] = _dtQuoteList.Rows[i]["ManufactYear"].ToString();
                _NameDriver[i] = _dtQuoteList.Rows[i]["NameDriverStatus"].ToString();

                DateTime _CoverageDate = dateTimeNow; 
                if(!DateTime.TryParse(_dtQuoteList.Rows[i]["CoverageCommenceDate"].ToString(), out _CoverageDate))
                {
                    _CoverageDate = dateTimeNow;
                }
                string commdate = string.Format("{0:dd}", _CoverageDate.Day.ToString("00"));
                commdate = commdate + "/" + string.Format("{0:MM}", _CoverageDate.Month.ToString("00"));
                commdate = commdate + "/" + string.Format("{0:yyyy}", _CoverageDate.Year.ToString());

                _PolicyStartDate[i] = commdate.ToString();
                _InsuranceCompany[i] = _dtQuoteList.Rows[i]["CurrentInsurer"].ToString();
                _Insurer[i] = _dtQuoteList.Rows[i]["CompanyName"].ToString();
                _ReferenceNumber[i] = _dtQuoteList.Rows[i]["QuoteRefNo"].ToString();
                _GarageType[i] = _dtQuoteList.Rows[i]["WorkShopDesc"].ToString();
                _BodilyInjury[i] = _dtQuoteList.Rows[i]["TPBIP"].ToString();
                _LiabliltyBody[i] = _dtQuoteList.Rows[i]["TPBIA"].ToString();
                _LiabliltyProperty[i] = _dtQuoteList.Rows[i]["TPPD"].ToString();
                _Deductible[i] = _dtQuoteList.Rows[i]["DEC"].ToString();
                _OwnDamage[i] = _dtQuoteList.Rows[i]["OwnDamage"].ToString();
                _FireTheft[i] = _dtQuoteList.Rows[i]["FireTheft"].ToString();
                if (_dtQuoteList.Rows[i]["FloodCover"] != DBNull.Value)
                {
                    _FloodCover[i] = _dtQuoteList.Rows[i]["FloodCover"].ToString();
                }
                else
                {
                    _FloodCover[i] = " ";
                }
                _PersonalAccident[i] = _dtQuoteList.Rows[i]["PADriver"].ToString();
                _BailBond[i] = _dtQuoteList.Rows[i]["BailBond"].ToString();
                _Compulsory[i] = _dtQuoteList.Rows[i]["TotalCMI"].ToString();
                _Voluntary[i] = _dtQuoteList.Rows[i]["TotalVMI"].ToString();
                _Duty[i] = "";
                _Vat[i] = "";
                _GrossPremium[i] = "";
                _Bank[i] = _dtQuoteList.Rows[i]["Bank"].ToString();
                _PaymentOption[i] = _dtQuoteList.Rows[i]["PaymentOption"].ToString();
                if (_PaymentOption[i] == "FP")
                {
                    _FullPayment[i] = Convert.ToSingle(_dtQuoteList.Rows[i]["Premium"].ToString()).ToString("#,000.00");
                    _NoofInstallments[i] = "3";
                }
                else if (_PaymentOption[i] == "IP")
                {
                    _FullPayment[i] = (Convert.ToSingle(_Compulsory[i].ToString()) + Convert.ToSingle(_Voluntary[i].ToString())).ToString("#,000.00");
                    _NoofInstallments[i] = _dtQuoteList.Rows[i]["NoofInstallMent"].ToString();
                }

                _InterestFree[i] = "Yes";
                if (_BrokerProvider[i].ToString() == "29" && _Bank[i].ToString() != "CHINS")
                {
                    if (_Bank[i].ToString() == "KBANK")
                    {
                        _InterestFree[i] = "Yes";
                    }
                    else
                    {
                        _InterestFree[i] = "No";
                    }
                    _InstallmentPayment[i] = Convert.ToSingle(_dtQuoteList.Rows[i]["IPFinalAnnualPremiumWD"].ToString()).ToString("#,000.00");
                }
                else
                {
                    _InstallmentPayment[i] = Convert.ToSingle(_dtQuoteList.Rows[i]["IPFinalAnnualPremiumWOD"].ToString()).ToString("#,000.00");
                }

                if (_PaymentOption[i] == "IP")
                {
                    if (_Bank[i].ToString() == "CHINS")
                    {
                        if (_NoofInstallments[i] == "4")
                        {
                            _MonthlyInstallment[i] = _NoofInstallments[i].ToString() + " (25:25:25:25)";
                        }
                        else if (_NoofInstallments[i] == "3")
                        {
                            _MonthlyInstallment[i] = _NoofInstallments[i].ToString() + " (40:30:30)";
                        }
                        else
                        {
                            _MonthlyInstallment[i] = _NoofInstallments[i].ToString() + " (50:50)";
                        }
                    }
                    else
                    {
                        _MonthlyInstallment[i] = _NoofInstallments[i].ToString() + "*(" + (Convert.ToSingle(_InstallmentPayment[i].ToString()) / (Convert.ToInt32(_NoofInstallments[i].ToString()))).ToString("#,000.00") + ")";
                    }

                    //Yui@15072014
                    if (_Bank[i].ToString() == "KBANK")
                    {
                        _CreditCard[i] = Resources.CarInsurance.KBANKCreditCard; //GetBankName(_BankCode); 
                    }
                    else
                    {
                        _CreditCard[i] = GetBankName(_Bank[i].ToString());
                    }
                }
                else
                {
                    _NoofInstallments[i] = "3";
                    _InstallmentPayment[i] = Convert.ToSingle(_dtQuoteList.Rows[i]["IPFinalAnnualPremiumWOD"].ToString()).ToString("#,000.00");
                    _MonthlyInstallment[i] = _NoofInstallments[i].ToString() + "*(" + (Convert.ToSingle(_InstallmentPayment[i].ToString()) / (Convert.ToInt32(_NoofInstallments[i].ToString()))).ToString("#,000.00") + ")";
                    _CreditCard[i] = Resources.CarInsurance.KBANKCreditCard; //GetBankName("KBANK");
                    _InterestFree[i] = "Yes";
                }
                _VehicleType[i] = " ";
                #endregion

                TotalFullPayment = TotalFullPayment + Convert.ToDecimal(_FullPayment[i].Replace(",", ""));
                TotalInstallPayment = TotalInstallPayment + Convert.ToDecimal(_InstallmentPayment[i].Replace(",", ""));
            }
        }
        string Empty = ".";
        Int32 TotalCalsPan = _QuoteCount + 1;
        Int32 CalsPan = _QuoteCount;

        #region Excel
        _html += "<html>";
        _html += "<head>";
        _html += "<meta http-equiv='content-type' content='text/html; charset=UTF-8'>";
        _html += "</head>";
        _html += "<body>";

        #region Company Details
        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr>";
        _html += "<td colspan='" + CalsPan.ToString() +  "'>&nbsp;</td>";
        _html += "<td><img src='http://www.gluaygluay.com/management/images/logos/gluaygluay_small.png' alt='gluaygluay' width='50px' height='40px' /></td>";
        _html += "</tr>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:22;'>Comparexpress Insurance broker ( Thailand ) Ltd</td></tr>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:22;'>Non-Life Insurance Broker Licensed Number ว00016/2553</td></tr>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:22;'>2 K.C.C Bdg, 2nd Floor Silom Soi9, Silom Road Bangrak Bangkok 10500</td></tr>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:22;'>Tel: 02-268-8222 fax 02-266-6339</td></tr>";
        _html += "</table>";

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "'>&nbsp;</td></tr>";
        _html += "</table>";

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:22; font-weight:bold;'>Fleet Car Insurance Quotes</td></tr>";
        _html += "<tr><td style='width:200px;' style=' height:22;'>Name</td><td colspan='" + CalsPan.ToString() + "'>: " + ContactPerson.ToString() + "</td></tr>";
        _html += "<tr><td style='width:200px;' style=' height:22;'>Contact No</td><td colspan='" + CalsPan.ToString() + "'>: " + ContactNo.ToString() + "</td></tr>";
        _html += "<tr><td style='width:200px;' style=' height:22;'>Fleet Reference Number </td><td colspan='" + CalsPan.ToString() + "'>: " + FleetRefNo.ToString() + "</td></tr>";
        _html += "</table>";
        #endregion

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "'>&nbsp;</td></tr>";
        _html += "</table>";

        #region Body
        _html += "<table width='100%' cellpadding='1' cellspacing='1' border='1'>";
        _html += "<tr>";
        _html += "<td align='left' style='background-color:#FFFF00; font-weight:bold; height:19;'>Number of Car</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#FFFF00; font-weight:bold;'>" + j.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Car Make / Model </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _CarMakeModel[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Vehicle type or usage</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _VehicleType[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Good record Discount (NCB) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _NCB[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Licensed Plate </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _LicensedPlate[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Year</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _Year[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Policy start Date</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _PolicyStartDate[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Insurance Company </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _InsuranceCompany[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#FFFF00; font-weight:bold; height:19;'>Policy Details</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#FFFF00; color:#FFFF00;'>" + Empty.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Insurance Company </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _Insurer[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Reference Number </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _ReferenceNumber[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Garage Type </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _GarageType[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#FFFF00; font-weight:bold; height:19;'>Third Party Cover</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#FFFF00; color:#FFFF00;'>" + Empty.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Bodily Injury/Death ( per person ) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _BodilyInjury[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Liablilty for Bodily Injury / Death </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _LiabliltyBody[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Liablilty for Property Damage  </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _LiabliltyProperty[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Deductible (per accident ) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _Deductible[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#FFFF00; font-weight:bold; height:19;'>Owner Damage Cover</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#FFFF00; color:#FFFF00;'>" + Empty.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Own Damage</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _OwnDamage[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Fire / Theft </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _FireTheft[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD;'>Flood Cover</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD; height:19;'>" + _FloodCover[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#FFFF00; font-weight:bold; height:19;'>Add. Cover. Per Endorsement </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#FFFF00; color:#FFFF00;'>" + Empty.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Personal Accident ( per person)</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _PersonalAccident[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Bail Bond ( per accident) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _BailBond[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>CMI ( Compulsory Insurance ) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _Compulsory[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>VMI ( Voluntary Insurance ) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _Voluntary[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#FFFF00; font-weight:bold; height:19;'>Payment Options : </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#FFFF00; color:#FFFF00;'>" + Empty.ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>1) Full Payment (+taxes & Duties) </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _FullPayment[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>2) Monthly Installment  </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _InstallmentPayment[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Number of Installments</td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _MonthlyInstallment[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>Credit Card by </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _CreditCard[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";

        _html += "<tr>";
        _html += "<td align='left' style='background-color:#BDBDBD; height:19;'>0% Interest Free </td>";
        for (int j = 1; j <= _QuoteCount; j++)
        {
            _html += "<td align='center' style='background-color:#BDBDBD;'>" + _InterestFree[j - 1].ToString() + "</td>";
        }
        _html += "</tr>";
        _html += "</table>";
        #endregion

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "'>&nbsp;</td></tr>";
        _html += "</table>";

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Total Full Payment</td><td colspan='" + CalsPan.ToString() + "'>: " + TotalFullPayment.ToString("#,000.00") + "</td></tr>";
        _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Total Installment Payment</td><td colspan='" + CalsPan.ToString() + "'>: " + TotalInstallPayment.ToString("#,000.00") + "</td></tr>";
        _html += "</table>";

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "'>&nbsp;</td></tr>";
        _html += "</table>";

        #region Remarks
        string _remarks = Resources.Proposal.RemarksMsg1;
        _remarks = _remarks.Replace("<br/>", "^");
        string[] Remarks = _remarks.Split('^');
        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:19; font-weight:bold;'>" + Resources.Proposal.Remarks + "</td></tr>";
        for (int a = 0; a < Remarks.Length; a++)
        {
            _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "' style=' height:19;'>" + Remarks[a].ToString() + "</td></tr>";
        }
        _html += "</table>";
        #endregion

        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td colspan='" + TotalCalsPan.ToString() + "'>&nbsp;</td></tr>";
        _html += "</table>";

        #region Agent Details
        _html += "<table width='100%' cellpadding='1' cellspacing='1'>";
        _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Broker</td><td colspan='" + CalsPan.ToString() + "'>: " + AgentName.ToString() + "</td></tr>";
        _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Email</td><td colspan='" + CalsPan.ToString() + "'>: " + AgentEmail.ToString() + "</td></tr>";
        _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Contact No</td><td colspan='" + CalsPan.ToString() + "'>: " + AgentContactNo.ToString() + "</td></tr>";
        if (AgentLicenseNo.ToString().Trim() != "")
        {
            _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>License No</td><td colspan='" + CalsPan.ToString() + "'>: " + AgentLicenseNo.ToString() + "</td></tr>";
        
        }
        else
        {
            _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Supervisor Name</td><td colspan='" + CalsPan.ToString() + "'>: " + AgentSupervisor.ToString() + "</td></tr>";
            _html += "<tr><td style='width:200px;' style=' height:22; font-weight:bold;'>Supervisor License No</td><td colspan='" + CalsPan.ToString() + "'>: " + AgentSupLicenseNo.ToString() + "</td></tr>";
        }
        _html += "</table>";
        #endregion

        _html += "</body>";
        _html += "</html>";
        #endregion

        lblContent.Text = _html;
        ExportGridView(_fileName, lblContent);

    }

    public void ExportGridView(string fileName, Label lblProposal, string headerText)
    {
        string attachment = "attachment; filename=" + fileName;
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        // Create a form to contain the grid
        HtmlForm frm = new HtmlForm();
        frm.InnerHtml = headerText;
        lblProposal.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(lblProposal);
        frm.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }

    public void ExportGridView(string fileName, Label lblContent)
    {
        string attachment = "attachment; filename=" + fileName + ".xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        Response.Write(lblContent.Text);
        Response.End();
    }

    private string GetExcelFilePath(Int64 CompanyId)
    {
        string _filePath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NonGGFileOutputPath").ToString();
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();
        string _currentMonth = dateTimeNow.ToString("yyyyMMM");
        string _todaydate = dateTimeNow.ToString("yyyyMMMdd");
        _filePath += "exceloutput\\fleet\\";
        if (!_myIO.CheckDirectory(_filePath + _currentMonth))
        {
            if (_myIO.CreateDirectory(_filePath, _currentMonth))
            {
                _filePath += _currentMonth + "\\";
            }
        }
        else
        {
            _filePath += _currentMonth + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + _todaydate))
        {
            if (_myIO.CreateDirectory(_filePath, _todaydate))
            {
                _filePath += _todaydate + "\\";
            }
        }
        else
        {
            _filePath += _todaydate + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + CompanyId.ToString()))
        {
            if (_myIO.CreateDirectory(_filePath, CompanyId.ToString()))
            {
                _filePath += CompanyId.ToString() + "\\";
            }
        }
        else
        {
            _filePath += CompanyId.ToString() + "\\";
        }
        return _filePath;
    }

    private string GetBankNames(string BankCode)
    {
        string _BankName = "";
        if (BankCode == "CHINS")
        {
            _BankName = Resources.CarInsurance.CashInstallment;
        }
        else if (BankCode == "BKK")
        {
            _BankName = Resources.CarInsurance.BankBKK;
        }
        else if (BankCode == "KBANK")
        {
            _BankName = Resources.CarInsurance.BankK;
        }
        else if (BankCode == "KTC")
        {
            _BankName = Resources.CarInsurance.BankKTC;
        }
        else if (BankCode == "CITI")
        {
            _BankName = Resources.CarInsurance.BankCITI;
        }
        else if (BankCode == "AYA")
        {
            _BankName = Resources.CarInsurance.BankAYA;
        }
        else if (BankCode == "CTRL")
        {
            _BankName = Resources.CarInsurance.CentralCard;
        }
        else if (BankCode == "RBSN")
        {
            _BankName = Resources.CarInsurance.RobinsonCard;
        }
        else if (BankCode == "HPRO")
        {
            _BankName = Resources.CarInsurance.HomeproCard;
        }
        return _BankName;
    }

    #endregion

}
